繁体   English   中英

Laravel:计算关系中的行数

[英]Laravel: Count number of rows in a relationship

我有以下关系:

  • 一个场地有很多优惠
  • 一个报价有很多订单

我有以下 Eloquent 模型来表示这一点:

class Venue {
    public function orders()
    {
        return $this->hasManyThrough(Order::class, Offer::class);
    }
}

我想使用 Laravel 的 Eloquent 模型确定location_id = 5场地的订单总数。

我设法做到这一点的唯一方法如下:

$venues = Venue::where('location_id', 5)->with('orders')->get();

$numberOfOrders = 0;
foreach($venues as $venue) {
    $numberOfOrders += $venue->orders->count();
}
dump($numberOfOrders); // Output a single number (e.g. 512)

但是,这显然不是很有效,因为我使用 PHP 而不是 SQL 计算计数。

我如何单独使用 Eloquent 模型来做到这一点。

您可以使用 Eloquent。 从 Laravel 5.3 开始,有withCount()

在你的情况下,你将有

$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();

然后通过这种方式访问​​它

foreach ($venues as $venue) {
    echo $venue->orders_count;
}

可以在这里找到参考: https : //laravel.com/docs/5.3/eloquent-relationships#querying-relations

如果您使用的是 Laravel 5.3 或更高版本,则可以使用withCount

如果您想计算关系中的结果数量而不实际加载它们,您可以使用 withCount 方法,它将在您的结果模型上放置一个 {relation}_count 列。 例如:

$venues = Venue::withCount(['orders'])->get;

foreach ($venues as $venue) {
    echo $venue->orders_count;
}

您可以在Laravel 文档中阅读有关withCount更多信息。

如果您使用的版本低于 5.3,您可以在您的Venue模型上创建自定义关系:

public function ordersCount()
{
    return $this->belongsToMany('App\Models\Order')
        ->selectRaw('venue_id, count(*) as aggregate_orders')
        ->groupBy('venue_id');
}

public function getOrderCount()
{
    // if relation is not loaded already, let's do it first
    if (!array_key_exists('ordersCount', $this->relations)) {
        $this->load('ordersCount');
    }

    $related = $this->getRelation('ordersCount')->first();
    // then return the count directly
    return ($related) ? (int) $related->aggregate_orders : 0;
}

然后可以用作: Venue::with('ordersCount'); . 这种自定义关系的好处是您只查询计数,而不是在不需要时查询所有这些关系。

$venues = Venue::with([
    'orders' => function ($q) {
        $q->withCount('orders');
    }
])->get();

然后以这种方式使用它来获取单个记录

$venues->first()->orders->orders_count();

或者,您也可以将这种方式用于集合

foreach($venues as $venue)
{
echo $venue->order_count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM