雄辩的groupBy()在表关系上无法正常工作 [英] Eloquent groupBy() is not working correctly on table relations
问题描述
groupBy
方法无法正常工作.我不确定是什么问题.
The groupBy
method isn't working correctly. I am not sure what is the problem.
我在表之间建立了hasMany()
<-> belongsTo()
关系.
I made made a hasMany()
<-> belongsTo()
relations between tables.
放置model
protected $table = "places";
protected $guarded = [];
public $with = ["plans"];
public function plans()
{
return $this->hasMany("App\Models\Plan");
}
计划Model
protected $guarded = [];
public function place()
{
return $this->belongsTo("App\Models\Place");
}
在 controller 中,当我返回json数据时,可以看到该关系.
In controller when I return json data I can see the relation.
$place = Place::with(["plans"])->get();
return $place;
结果很好.检查图片: https://imgur.com/a/0CHXPhQ
The result is fine with this. check the image: https://imgur.com/a/0CHXPhQ
但是,当我尝试在place_name
列上使用groupBy()
时.它并没有将他们的计划集中在一个地方...
But, when I try to use groupBy()
on place_name
column. It doesn't group the their plans in one place...
Place::with(["plans"])->groupBy("place_name")->get();
及其结果: https://imgur.com/a/qPxMU42
正如您所看到的,第二名的计划与第一名没有分组...已经不明了...预期结果计划对象也应该分组,因为他们的place_name
已分组...
As you see second place's plan doesn't group with first place... it's gone unknown... Expected result plan object should grouped too because their place_name
grouped...
任何想法导致此问题的原因是什么?我该如何解决?
Any idea what's causing this problem? How can I fix it?
推荐答案
如果由于group by的原因有时会遇到两行分组的问题,那么您可以做一件事.您可以在两个字段中同时使用group by.
If you are facing a problem that sometimes two rows are grouping due to group by, then you can do one thing. You can use group by concat both fields.
$data = Place::groupBy(\DB::raw('CONCAT(name, ' ', address)'))->paginate();
这是您可以用来获得期望结果的逻辑.
This is the logic you can put and get desire result.
这篇关于雄辩的groupBy()在表关系上无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!