我试图在我的功能中返回一个雄辩的集合,所以我这样做了:
// model
// User.php
// user -> branch -> groups -> alerts
public function alerts()
{
$alerts = (new Alert)->newCollection(); // empty elequent collection
$groups = $this->branch()->first()->groups()->get(); // collection of group model
foreach ($groups as $group) {
// merge all groups alerts to an single eloquent collection
$alerts->merge($group->alerts()->get());
}
return $alerts;
}然而,我知道我的数据库中有一些数据,我检查了它们。在我的情况下,$alerts不能是空的!
如果我是dd($alerts),那么只有一组empty雄辩的集合。
// dd($alerts)
Illuminate\Database\Eloquent\Collection {#1423 ▼
#items: []
}另外,我知道push和concat方法,但是concat也不起作用,push不做我想做的事情。
我知道我可以做联接表,但也不想使用联接。
如何正确地合并雄辩的集合?
谢谢。
发布于 2020-09-27 12:33:16
foreach ($groups as $group) {
$alerts = $alerts->merge($group->alerts()->get());
}您忘记分配合并的集合。
https://stackoverflow.com/questions/64088424
复制相似问题