Laravel渴望加载计数关系 [英] Laravel eager loading count relation

查看:83
本文介绍了Laravel渴望加载计数关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型,Order,OrderProduct和Product. OrderProduct是用于从Order和Product创建关系的表,该关系存储诸如价格或数量之类的信息.在我的产品列表操作中,我需要显示每个产品有多少个未完成订单(待处理或已付款).因此,我试图像这样加载这种关系:

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

还有

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

我只想要计数reserved_stock: 4.

有什么想法吗?

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

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.

推荐答案

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

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

这篇关于Laravel渴望加载计数关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆