php - laravel eager load through model
问题描述
I have 3 tables with this relationship:
- User (hasOne store, hasMany products)
- Product (Belongs to user)
- Store (belongs to user)
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();
解决方案
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');
}
推荐阅读
- matlab - 使用 fmincon() 求解一个特殊的非线性程序
- get - 如何从 FTP 中获取具有特定名称的文件夹和子文件夹
- typescript - 如何理解类型 any、unknown、{} 之间以及它们与其他类型之间的关系?
- php - 在 laravel 中为未登录用户授权资源
- django - 特定 URL 调用
- python-sphinx - 如何在 Sphinx 中确保正确的智能报价?
- php - PHP / MySQL:来自 MySQL 的数据不显示在选择选项中(下拉列表)
- azure - 防止 Azure Live Metrics Stream 将每次轮询记录到队列中
- php - Php: Email received without any messages
- c++ - 传递可变参数时在成员初始化器列表中进行强制转换