【问题标题】:Laravel with([]) select only some columns of the relationLaravel with([]) 仅选择关系的某些列
【发布时间】:2020-10-15 17:16:39
【问题描述】:

编辑

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

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

假设你有一个大的 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);

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

我遇到了同样的问题。您需要指定 foreign id 而不是 id(主键)

例如:

Data::with('other:id,name')->get();

如果您自定义外国名称,它将无法正常工作。 因此,您需要完全添加您的外国列名

Data::with('other:foreign_id,name')->get();

这会奏效的!

【讨论】:

    【解决方案2】:
    $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);
    

    【讨论】:

      【解决方案3】:

      像这样:

      $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);
      

      documentation 非常简短地介绍了特定列的加载(您甚至必须向下滚动一点到“急切加载特定列”的标题)。

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

      $books = App\Book::with('author:id,name')->get();
      

      注意:

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

      【讨论】:

      • 请描述你的答案。
      • @unclexo 更好吗?
      • 是的。非常感谢!
      【解决方案4】:

      您还可以为一些更高级的关系查询提供回调。

      Order::with([
          'company' => function ($q) {
               $q->select('id', 'name');
          }
      ])
      

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2019-04-18
        • 1970-01-01
        • 2014-09-21
        • 2012-08-08
        相关资源
        最近更新 更多