3

I have two tables, users and products. Products table structure is:

id product_name user_id isGlobal
1 apple 10 0
2 banana 10 1
3 pear 20 0
4 melon 30 0

Here is User model where made relation with products

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

Controller which i'm getting products

$products = $user->product()->get();

Problem: Product with isGlobal = 1 param must be shown for every user.

How can solve this?


PS: below solution did not work.

public function product()
{
    return $this->hasMany(Product::class)->where('isGlobal', 1);
}
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Hayrulla Melibayev
  • 462
  • 1
  • 5
  • 20

1 Answers1

0

You have to apply your condition in 2 places:

  • In hasMany Relation
  • Eager loading conditions

So for first:

public function products()
{
     return $this->hasMany(Product::class)->where('isGlobal', 1);
}

this will work for conditions when you want to access the data this way:

$products = $user->products;

But this won't work for eager loading situation like:

$users = User::with('products')->get();

so you have to apply the condition on all of your eager loading situations like this:

$users = User::with('products' => function($query) {
    $query->where('isGlobal', 1);
})->get();
Mohsen Nazari
  • 1,281
  • 1
  • 3
  • 13