php - Laravel - Eager Loading BelongsToMany 关系
问题描述
我在两个实体/表之间有一对多的关系。
/**
* Get all of the products.
*/
public function products()
{
return $this->belongsToMany(Product::class)->select(
[
'products.id',
'products.title',
'products.sku',
'automation_products.automation_id as auto_id',
'display_order',
]
)->orderBy('display_order');
}
当我想急切加载这种关系时,似乎有重复的查询在后台运行。我使用此代码急切加载我的关系:
$automation = \App\Models\Automation::with('products')->whereId(1)->get()->first();
dump($automation->products()->get());
dump($automation->products()->get());
dump($automation->products()->get());
有什么我想念的吗?
谢谢回复。
解决方案
渴望将负载关系加载到模型属性中。
您可以像访问此属性一样$automation->products
- 无论她被调用多少次 - 查询将在急切的负载下执行一次。
但是,当您调用 like ->products()->get()
- eloquent 执行查询时,因为您告诉“现在的get()
关系products()
”
推荐阅读
- java - 尽管 Pixel 2 存在于传感器列表中,但无法在 Pixel 2 上获取磁场传感器
- cordova - 如何在我的 react 本机版本的应用程序中访问在 cordova/phonegap 应用程序中创建的 localStorage 中的数据?
- ios - 使用 Swift 中的块调用 Objective C 方法
- r - 如何修复“`$<-.data.frame` 替换错误有 x 行,数据有 y”?
- matlab - Traci4matlab:如何解决“使用 traci.socket 时出错”?
- javascript - 在 IE、Edge 和 Chrome 上单击提交按钮后,Flask 应用程序不会执行(仅在 Firefox 上)
- api - openapi3 - 如何发出错误请求示例
- batch-file - 执行.bat时如何隐藏cmd提示?
- flutter - Flutter hot reload 和 Navigator.push in onTap
- java - 是否有一种内存有效的方法来转换输入流编码