Laravel eager loading count relation

此生再无相见时 提交于 2019-12-14 02:12:39

问题


I have three models, Order, OrderProduct and Product. OrderProduct is the table that create the relation from Order and Product that stores information like price or quantity. In my product list action i need to show how many orders are open (pending or paid) for each product. So i'm trying to eager load this relation like this:

// ProductController.php

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

    return $data;
}

And

//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]);
}

It works but the response from it is an array like this:

{
    "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
        }
    ]
}

I want only the count reserved_stock: 4.

Any ideas about how doing it?

ps: I've already tried doing withCount bit with it i'm not able to create the join from orders table to filter by order status.


回答1:


You can do something as follows, the relation might need some tinkering:

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;
}

and can be used as follows:

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

Product->getReservedStockCount();


来源:https://stackoverflow.com/questions/43870363/laravel-eager-loading-count-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!