>Edit
这个问题是独一无二的,因为它提出了独特的问题,例如:
- 与组件内的关系。(项目.产品.库存管理(。
- 大量的组件,这会导致链接问题的接受答案不适用。
假设你有一个大的 with((,如下所示:
$order = Order::with([
'company',
'complaints',
'person',
'items',
'items.product',
'items.product.stockManagement',
'status',
])->findOrFail($id);
然后,我如何选择它们的所有关系,但其中一些的特定列?
$order = Order::with([
'company', // select only id,name, size
'complaints', // select only id, name , body
'person',
'items',
'items.product', // select only id, name , price
'items.product.stockManagement',
'status', // select only id
'items.product.media',
'items.product.mainProduct',
'items.product.mainProduct.media'
])->findOrFail($id);
像这样:
$order = Order::with([
'company:id,name,size',
'complaints:id,name,body',
'person',
'items',
'items.product:id,name,price',
'items.product.stockManagement',
'status:id',
'items.product.media',
'items.product.mainProduct',
'items.product.mainProduct.media'
])->findOrFail($id);
该文档非常简短地介绍了特定列的加载(您甚至必须向下滚动到"预先加载特定列"的标题(。
您可能并不总是需要要检索的关系中的每一列。因此,Eloquent 允许您指定要检索关系的哪些列:
$books = AppBook::with('author:id,name')->get();
注意:
使用此功能时,应始终在要检索的列列表中包括id 列和任何相关的外键列。
您还可以为一些更高级的关系查询提供回调。
Order::with([
'company' => function ($q) {
$q->select('id', 'name');
}
])
我遇到了同样的问题。您需要指定foreign id
非 id(主键(。
例如:
Data::with('other:id,name')->get();
如果您自定义外语名称,它将不起作用。 因此,您需要完全添加外部列名称。
Data::with('other:foreign_id,name')->get();
那会起作用!
$order = Order::with(
['company' => function($query) {
$query->select('id','name','size')
}),
'complaints' => function($query) {
$query->select('id','name','body')
}),
'person',
'items',
'items.product' => function($query) {
$query->select('id','name','price')
}), 'items.product.stockManagement','status'=> function($query) {
$query->select('id')
}),'items.product.media', 'items.product.mainProduct', 'items.product.mainProduct.media'])->findOrFail($id);