laravel-7 Elequent 集合合并不工作
laravel-7 elequent collection merge not working
我试图在我的函数中 return 一个 eloquent 集合,所以我这样做了:
// 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
组 eloquent 集合。
// dd($alerts)
Illuminate\Database\Eloquent\Collection {#1423 ▼
#items: []
}
我也知道 push
和 concat
方法,但是 concat
也不起作用,并且 push
没有做我想做的事。
我知道我可以连接表,但不想也使用连接。
如何正确合并 eloquent 集合?
谢谢。
foreach ($groups as $group) {
$alerts = $alerts->merge($group->alerts()->get());
}
您忘记分配合并的集合。
我试图在我的函数中 return 一个 eloquent 集合,所以我这样做了:
// 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
组 eloquent 集合。
// dd($alerts)
Illuminate\Database\Eloquent\Collection {#1423 ▼
#items: []
}
我也知道 push
和 concat
方法,但是 concat
也不起作用,并且 push
没有做我想做的事。
我知道我可以连接表,但不想也使用连接。
如何正确合并 eloquent 集合?
谢谢。
foreach ($groups as $group) {
$alerts = $alerts->merge($group->alerts()->get());
}
您忘记分配合并的集合。