Laravel:计算关系中的行数

Yah*_*din 4 laravel eloquent laravel-5 laravel-5.1

我有以下关系:

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

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

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

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

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

$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)
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

您可以使用Eloquent。自Laravel 5.3起withCount()

就您而言,您将拥有

$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();
Run Code Online (Sandbox Code Playgroud)

然后以这种方式访问​​它

foreach ($venues as $venue) {
    echo $venue->orders_count;
}
Run Code Online (Sandbox Code Playgroud)

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