【问题标题】:laravel eager load through modellaravel 通过模型急切加载
【发布时间】:2019-08-06 17:04:11
【问题描述】:

我有 3 个具有这种关系的表:

  • 用户(hasOne 商店,hasMany 产品)
  • 产品(属于用户)
  • 商店(属于用户)

现在,如果我想在用户商店中获取用户产品,我会这样做:

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

但我想要的是这样的:

public function show($id)
    {
        $store = Store::where('id', $id)->with('products')->first();
        return view('admin.stores.show', compact('store'));
    }

问题

我如何在productsstores 之间建立关系,因为它们的user_id 列可以避免这条线:

$products = Product::where('user_id', $store->user_id)->get();

【问题讨论】:

  • 试试这个$store = Store::where('id', $id)->with('users.products')->first();
  • @shihab 好的返回数据但没有更清洁的方法吗?因为现在我必须循环像 @foreach($store->user->products as $product) 这样的产品不能像 @foreach($store->products as $product)

标签: php laravel


【解决方案1】:

也许您应该在StoreProduct 之间添加关系。将此添加到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');
}

【讨论】:

  • 好的,但你需要编辑你的答案 1products() 而不是 product() 就像 hasMany 2 它需要第二个 'user_id' 与产品模型中的一样然后它会工作
猜你喜欢
  • 1970-01-01
  • 2013-06-10
  • 2013-05-16
  • 2021-11-29
  • 2020-09-08
  • 2013-03-27
  • 2015-06-19
  • 2019-05-19
相关资源
最近更新 更多