Laravel在急切加载集合时选择特定列

时间:2015-03-06 11:29:48

标签: php laravel laravel-4 orm eloquent

获取以下代码段。我正在加载OrderDetail模型,其关系为Inventory

// Load order details for live orders and inventory ids
$order_details = \OrderDetail::whereIn('order_id', $live_order_ids)
    ->whereIn('inventory_id', $inventory_ids)
    ->with('inventory')
    ->get();

加载集合后,我正在进行以下处理:

// Deduct reserved stock from live un-picked orders
foreach ($order_details as $detail)
    if (array_key_exists($detail->inventory->sku, $free_stocks))
        $free_stocks[$detail->inventory->sku] -= 
            ($detail->qty_ordered - $detail->qty_picked);

如您所见,从加载的集合中,我只需要以下内容:

  • order_details.qty_ordered
  • order_details.qty_picked
  • inventory.sku

我希望对此进行优化并仅加载我需要的内容,即指明我要从主表和相关表中加载哪些列。

我该怎么做?当我尝试以下操作时,它似乎无法工作:

// Load order details for live orders and inventory ids
$order_details = \OrderDetail::whereIn('order_id', $live_order_ids)
    ->whereIn('inventory_id', $inventory_ids)
    ->with('inventory')
    ->get(['qty_ordered','qty_picked','sku']);

// Load order details for live orders and inventory ids
$order_details = \OrderDetail::whereIn('order_id', $live_order_ids)
    ->whereIn('inventory_id', $inventory_ids)
    ->with(['inventory' => function($query) {
        $query->addSelect(['id','sku']);
    }])
    ->get(['qty_ordered','qty_picked']);

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要使用select in query来获取所选列。或者,如果它不起作用,您需要使用laravel连接。

另请参阅laravel官方文档中的查询中的选择列。 http://laravel.com/docs/4.2/queries

// Load order details for live orders and inventory ids
$order_details = \OrderDetail::whereIn('order_id', $live_order_ids)
    ->whereIn('inventory_id', $inventory_ids)
    ->with(['inventory' => function($query) {
        $query->addSelect(['id','sku']);
    }])
    ->select('qty_ordered','qty_picked')
->get();