【发布时间】: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'));
}
问题
我如何在products 和stores 之间建立关系,因为它们的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)