首页 > 解决方案 > 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();

标签: phplaravel

解决方案


Store也许你应该添加和 之间的关系Product。将此添加到Store模型中:

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

这要Product

public function store()
{
    return $this->belongsTo(Store::class, 'user_id', 'user_id');
}

推荐阅读