Reputation: 7138
I have 3 tables with this relationship:
Now if I want get user products inside user store currently i do this:
public function show($id)
{
$store = Store::findOrFail($id);
$products = Product::where('user_id', $store->user_id)->get();
return view('admin.stores.show', compact('store', 'products'));
}
But what I'd like to have is something like:
public function show($id)
{
$store = Store::where('id', $id)->with('products')->first();
return view('admin.stores.show', compact('store'));
}
How can I make relation between products
and stores
due to their user_id
column to avoid this line:
$products = Product::where('user_id', $store->user_id)->get();
Upvotes: 0
Views: 34
Reputation: 671
Maybe you should add relationship between Store
and Product
. Add this to Store
model:
public function products()
{
return $this->hasMany(Product::class, 'user_id', 'user_id');
}
and this to Product
:
public function store()
{
return $this->belongsTo(Store::class, 'user_id', 'user_id');
}
Upvotes: 2