Pedro Pedro - 1 month ago 9
PHP Question

count total products from users galleries

im trying to create a query that counts the total products from a user, but my code isnt working, i leave above my code:

Tables:
Galleries:

- id;
- title

Products
- id;
- gallery_id;
- title;
- price


Models:
Gallery

public function products(){
return $this->hasMany(Product::class);
}


My query:

$totalProducts = Gallery::where('user_id', $userId)->products()->count();


Error:

Non-static method App\Gallery::products() should not be called statically, assuming $this from incompatible context

Answer

If you want to count products of one gallery, you need to get the object:

$totalProducts = Gallery::where('user_id', $userId)->first()->products()->count();

If you want to count all products of a user, you should add HasManyThrough relation first:

public function userProducts()
{
    return $this->hasManyThrough('App\Product', 'App\Gallery');
}

Then count products:

User::find($id)->userProducts()->count();
Comments