这并不是真正的 Eloquent,要将 Eloquent 模型添加到您的集合中,您有一些选择:
在 Laravel 5 中,您可以从助手中受益
$c = collect(new Post);
或者
$c = collect();
$c->add(new Post);
旧 Laravel 4 答案
$c = new \Illuminate\Database\Eloquent\Collection;
然后你可以
$c->add(new Post);
或者你可以使用make:
$c = Collection::make(new Post);
从 Laravel 5 开始。我使用全局函数 collect()
$collection = collect([]); // initialize an empty array [] inside to start empty collection
这种语法非常简洁,如果您不想要数字索引,也可以添加偏移量,如下所示:
$collection->offsetSet('foo', $foo_data); // similar to add function but with
$collection->offsetSet('bar', $bar_data); // an assigned index
实际上,我发现使用 newCollection()
更具前瞻性....
例子:
$collection = (new Post)->newCollection();
这样,如果您决定在稍后阶段为您的模型创建自己的集合类(就像我已经做过多次一样),重构代码会容易得多,因为您只需覆盖模型中的 newCollection()
函数
拉拉维尔> = 5.5
这可能与原始问题无关,但由于它是谷歌搜索中的第一个链接之一,我发现这对像我这样正在寻找如何创建空集合的人很有帮助。
如果您想手动创建一个新的空集合,您可以像这样使用 collect
辅助方法:
$new_empty_collection = collect();
您可以在 Illuminate\Support\helpers.php
中找到此帮助程序
片段:
if (! function_exists('collect')) {
/**
* Create a collection from the given value.
*
* @param mixed $value
* @return \Illuminate\Support\Collection
*/
function collect($value = null)
{
return new Collection($value);
}
}
collect()
助手已经被编辑到接受的答案中。
Illuminate\Database\Eloquent\Collection
类型的空集合?
只是为了添加到接受的答案,您还可以在 config/app.php
中创建一个别名
'aliases' => array(
...
'Collection' => Illuminate\Database\Eloquent\Collection::class,
然后你只需要做
$c = new Collection;
在 Laravel 5 和 Laravel 6 中,您可以从服务容器中解析 Illuminate\Database\Eloquent\Collection
类,然后将模型添加到其中。
$eloquentCollection = resolve(Illuminate\Database\Eloquent\Collection::class);
// or app(Illuminate\Database\Eloquent\Collection::class). Whatever you prefer, app() and resolve() do the same thing.
$eloquentCollection->push(User::first());
有关了解在 laravel 中从服务容器中解析对象的更多信息,请查看此处:https://laravel.com/docs/5.7/container#resolving
我正在使用这种方式:
$coll = new Collection();
$coll->name = 'name';
$coll->value = 'value';
$coll->description = 'description';
并将其用作正常的 Collection
dd($coll->name);
在 $this->collection->make([])
之后使用注入模式比使用 new Collection
更好
use Illuminate\Support\Collection;
...
// Inside of a clase.
...
public function __construct(Collection $collection){
$this->collection = $collection;
}
public function getResults(){
...
$results = $this->collection->make([]);
...
}
不定期副业成功案例分享
\Illuminate\Support\Collection
是\Illuminate\Database\Eloquent\Collection
的更通用版本。所以我想,它毕竟是 Eloquent 的一部分。希望这对其他人有帮助。\Illuminate\Support\Collection
,您可以使用$c->push(new Post);
而不是 add 方法。$c = \Illuminate\Database\Eloquent\Collection::make();
。这确保了正确的工厂实例化。Illuminate\Database\Eloquent\Collection
与\Illuminate\Support\Collection
不同。第一个具有使用模型的特定方法