2017-05-09 14 views
2

私は3つのモデル、Order、OrderProduct、Productを持っています。 OrderProductは、価格や数量などの情報を格納するOrderとProductの関係を作成するテーブルです。私の商品リストのアクションでは、各商品のために何個の注文が開いている(保留中か支払っている)かを示す必要があります。だから私はこのように、この関係熱心な負荷にしようとしている:Laravel eager loading count relation

// 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ビットを実行しようとしました。私はオーダーステータスでフィルタリングするためにordersテーブルからjoinを作成することができません。

+0

はおそらくあなたを助けるます。http:// stackoverflowの.com/questions/20770284/laravel-hasmany-relation-count-number-of-likes-and-comments-on-post – Daan

+0

@Daanそれは熱心な読み込みではありません。私は私のすべての製品のために1つだけの質問をしたい。あなたの参照に続いて、彼はカウントである別の属性を作成し、foreachなどでこれを呼び出します。私はそれを表示する前にロードする必要があります。 –

+0

カウント番号のみを返すことができます。 'return count($ 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

うれしい私は助けることができました! –

関連する問題