gpt4 book ai didi

mysql - 如何在 Laravel 5 中多次加入和使用 withCount

转载 作者:行者123 更新时间:2023-11-30 22:14:56 25 4
gpt4 key购买 nike

我有 3 个模型:Vehicle、Dealer 和 Province

Eloquent关系如下:

Vehicle belongsTo Dealer

Dealer hasMany Vehicles

Province hasMany Dealers

Dealer belongs to Province

我想列出每个省份的车辆数量,而省份仅通过经销商与车辆相关联。

我的代码:

$provinces = Province::withCount('dealers')->get();

foreach ($provinces as $province) {
echo $province->dealers_count;
}

这段代码可以得到每个省的经销商数量,但是操纵这段代码无法得到每个省的车辆数量。任何想法

最佳答案

假设您的模型设置正确,我可以将其添加到我的省份模型中。

public function vehicles()
{
return $this->hasManyThrough(Vehicle::class, Dealer::class);
}

然后我就这样用了...

$provinces = App\Province::with('vehicles')->get();

foreach ($provinces as $province) {
echo $province->vehicles->count();
}

关于mysql - 如何在 Laravel 5 中多次加入和使用 withCount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38726192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com