我有一个类 Place,有时,在我的主 Sample 对象中,我有多个位置,因此我调用 Sample->places 将其发送到我的视图。
但对于一个新样本,我里面没有 Place 对象,所以我想在空集合中添加一个:
Illuminate\Database\Eloquent\Collection {#513 ▼
#items: []
#escapeWhenCastingToString: false
}
如何在 items 集合数组中添加 Place 的新实例?
我的搜索返回这篇文章在 laravel 集合对象中添加新元素它已关闭并且令人困惑,因为集合变量被命名为 $items。
在我的情况下,sample有(或没有)place,我通过写来解决:
$sample_places = $sample_record->places;
if ($sample_places->isEmpty()) {
$sample_places->push(new Place());
}
所以我的收藏现在有一个项目,它是一个空的 Place 实例
Illuminate\Database\Eloquent\Collection {#513 ▼
#items: array:1 [▼
0 => App\Models\Place {#500 ▶}
]
#escapeWhenCastingToString: false
}
我可以将此集合提供给我的视图以渲染表单来填充第一个位置。