提问者:小点点

拉韦尔负荷计数关系


我有三种型号,订单、订单产品和产品。OrderProduct是从订单和存储价格或数量等信息的产品创建关系的表。在我的产品列表操作中,我需要显示每个产品有多少未结订单(待定或已付款)。所以我试着像这样加载这个关系:

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

我只想要数量保留库存:4

你知道怎么做吗?

ps:我已经尝试了用它做with Count位,我不能创建从订单表到按订单状态过滤的连接。


共1个答案

匿名用户

您可以执行以下操作,关系可能需要一些修补:

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