php - Laravel 急切加载计数关系

标签 php laravel eager-loading

我有三个模型:Order、OrderProduct 和 Product。 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
        }
    ]
}

我只想要数量 reserved_stock: 4

关于如何做到这一点有什么想法吗?

ps:我已经尝试使用它进行 withCount 位,但我无法从订单表创建联接以按订单状态进行过滤。

最佳答案

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

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

关于php - Laravel 急切加载计数关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870363/

相关文章:

ruby-on-rails - Rails 5 Eager load 然后 find_by

php - 获取 PDO 中更新行的 ID

php - Docker 服务分离

php - Laravel 5.3,用图像替换分页链接(<< 和 >>)

php - laravel - 使用 select() 和 with() 进行查询不起作用

nhibernate - 为什么 NHibernate 不急切地获取我的数据

php - 如何使用 PHP 将图像发送到 deviantsart Rest API

php - 在 WooCommerce 3+ 中将购物车总数作为 float 获取

php - Laravel Cashier 创建订阅

php - 预加载参数 - laravel