mafortis
mafortis

Reputation: 7138

laravel eager load through model

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'));
    }

Question

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

Answers (1)

Sergey Bogdanov
Sergey Bogdanov

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

Related Questions