staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Add withCount in hasManyDeepFromRelations #236

Closed luccui000 closed 4 months ago

luccui000 commented 4 months ago

Hi @staudenmeir, can you add a function so that I can use withCount for hasManyDeepFromRelations?

staudenmeir commented 4 months ago

Hi @luccui000, How do you mean? How exactly do you want to use withCount()?

luccui000 commented 4 months ago

Sorry for replying late !

For example, I have a relationship user -> hasOne -> favourite -> hasMany -> products. Now, I want to count the number of products for that user: $user->withCount([‘products’]). It will be something like that.

staudenmeir commented 4 months ago

You can achieve this with a native HasManyThrough relationship: https://laravel.com/docs/11.x/eloquent-relationships#has-many-through

class User extends Model
{
    public function products(): HasManyThrough
    {
        return $this->hasManyThrough(Product::class, Favorite::class);
    }
}