2017-05-09 70 views
2

我有三个型号,订购,OrderProduct和产品。 OrderProduct是创建存储信息(如价格或数量)的Order和Product关系的表。在我的产品清单行动中,我需要显示每件产品有多少订单已开启(挂起或付款)。所以我想急于负载这种关系是这样的:Laravel预先加载计数关系

// ProductController.php 

public function index() 
{ 
    $data = Product::with(['reservedStock']); 

    return $data; 
} 

而且

//Product.php 

public function reservedStock() 
{ 
    return $this->hasMany(OrderProduct::class, 'product_sku') 
     ->selectRaw('order_products.product_sku, count(*) as count') 
     ->join('orders', 'orders.id', 'order_products.order_id') 
     ->whereIn('orders.status', [Order::STATUS_PENDING, Order::STATUS_PAID]); 
} 

它的工作原理,但是从它的反应是这样的一个数组:

{ 
    "sku": 384, 
    "brand_id": null, 
    "line_id": null, 
    "title": "Alcatel Pixi 4 Colors OT4034E 8GB 3G Preto", 
    "ean": null, 
    "ncm": 85171231, 
    "price": "315.44", 
    "cost": "0.00", 
    "condition": 0, 
    "warranty": null, 
    "created_at": "2016-08-25 10:45:40", 
    "updated_at": "2017-03-30 17:51:07", 
    "deleted_at": null, 
    "reserved_stock": [ 
     { 
      "product_sku": 384, 
      "count": 4 
     } 
    ] 
} 

我想只有计数reserved_stock: 4

如何做任何想法?

PS:我已经尝试过做withCount位与它我无法创建订单表的连接通过订单状态进行过滤。

+0

读这可能会帮助您:HTTP://计算器.COM /问题/ 20770284/laravel-的hasMany - 关系 - 数数 - 的 - 喜欢 - 和 - 评论 - 在岗 – Daan

+0

@Daan它不是预先加载。我只想为我的所有产品提供一个查询。在你引用之后,他创建了另一个属性count,然后我把它称为foreach或其他东西。我需要在显示之前加载它。 –

+0

您只能返回计数数字。 '返回计数($ product-> reservedStock);'? –

回答

2

你可以做一些如下的关系可能需要一些修补:

public function reservedStockCount() 
{ 
    return $this->belongsToMany(OrderProduct::class) 
     ->selectRaw('order_products.id, count(*) as aggregate_reserved_stock') 
     ->join('orders', 'orders.id', 'order_products.order_id') 
     ->whereIn('orders.status', [Order::STATUS_PENDING, Order::STATUS_PAID]); 
     ->groupBy('order_products.id'); 
} 

public function getReservedStockCount() 
{ 
    // if relation is not loaded already, let's do it first 
    if (!array_key_exists('reservedStockCount', $this->relations)) { 
     $this->load('reservedStockCount'); 
    } 

    $related = $this->getRelation('reservedStockCount')->first(); 
    // then return the count directly 
    return ($related) ? (int) $related->aggregate_reserved_stock : 0; 
} 

,可以使用如下:

Product::with(['reservedStockCount']); 

Product->getReservedStockCount(); 
+0

它的工作!因为我用laravel作为API,我需要创建一个自定义属性和使用方法,其追加到我的模型。谢谢! –

+2

很高兴能帮到你! –