在 Laravel 4 中,如果不使用查询构建器,我们该如何创建新的 Eloquent Collection?
有一个方法叫做
我考虑创建一个空的 Collection,然后用 Eloquent 对象填充它。我之所以不使用数组,是因为我喜欢 Eloquent Collections 的方法,比如
如果有其他选择,我很乐意听听。
有一个方法叫做
newCollection()
可以被重写,但实际上它并没有什么用处,因为它仅在查询结果集时使用。我考虑创建一个空的 Collection,然后用 Eloquent 对象填充它。我之所以不使用数组,是因为我喜欢 Eloquent Collections 的方法,比如
contains
。如果有其他选择,我很乐意听听。
\Illuminate\Support\Collection
是\Illuminate\Database\Eloquent\Collection
的更通用版本。所以,我猜它毕竟是Eloquent的一部分。希望这对其他人有所帮助。 - JofryHS\Illuminate\Support\Collection
,你可以使用$c->push(new Post);
代替add方法。 - Rogier$c = \Illuminate\Database\Eloquent\Collection::make();
。这样可以确保正确的工厂实例化。 - SoulriserIlluminate\Database\Eloquent\Collection
不同于\Illuminate\Support\Collection
。前者具有与模型一起使用的特定方法。 - Javis