Laravel:计算关系中的行数 [英] Laravel: Count number of rows in a relationship
问题描述
我有以下关系:
- 一个场馆有很多优惠
- 要约有很多订单
我有以下雄辩的模型来表示这一点:
I have the following Eloquent model to represent this:
class Venue {
public function orders()
{
return $this->hasManyThrough(Order::class, Offer::class);
}
}
我想使用Laravel的Eloquent模型确定location_id = 5
场所的订单总数.
I want to determine the total number of orders for venues with location_id = 5
using Laravel's Eloquent model.
我设法做到这一点的唯一方法如下:
The only way I managed to do this is as follows:
$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来计算计数.
However, this is obviously not very efficient as I am calculating the count using PHP instead of SQL.
如何单独使用Eloquent模型来做到这一点.
How can I do this using Eloquent model alone.
推荐答案
您可以使用Eloquent.从Laravel 5.3开始,存在withCount()
.
You can use Eloquent. As of Laravel 5.3 there is withCount()
.
根据您的情况,您将拥有
In your case you will have
$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();
然后以这种方式访问
Then access it this way
foreach ($venues as $venue) {
echo $venue->orders_count;
}
可以在此处找到参考: https://laravel.com/docs/5.3 /eloquent-relationships#querying-relations
Can find reference here: https://laravel.com/docs/5.3/eloquent-relationships#querying-relations
这篇关于Laravel:计算关系中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!