Laravel with([]) 只选择关系的一些列

Pet*_*leg 1 php laravel eloquent

编辑

这个问题很独特,因为它提出了独特的问题,例如:

  1. 与组件之间的关系。(items.product.stockManagement)。
  2. 大量组件,这导致链接问题的公认答案不适用。

假设你有一个像下面这样的大 with():

$order = Order::with([
        'company',
        'complaints',
        'person',
        'items',
        'items.product',
        'items.product.stockManagement',
        'status', 
    ])->findOrFail($id);
Run Code Online (Sandbox Code Playgroud)

然后我如何选择他们的所有关系,但为其中一些选择特定的列?

$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);
Run Code Online (Sandbox Code Playgroud)

Dou*_*aan 5

像这样:

$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);
Run Code Online (Sandbox Code Playgroud)

文档非常简要地介绍了特定列的加载(您甚至必须向下滚动到显示“急切加载特定列”的标题)。

您可能并不总是需要正在检索的关系中的每一列。因此,Eloquent 允许您指定要检索的关系列:

$books = App\Book::with('author:id,name')->get();
Run Code Online (Sandbox Code Playgroud)

笔记:

使用此功能时,您应该始终在要检索的列列表中包含id 列和任何相关的外键列