Ant*_*iro 87
这不是真正的雄辩,要为您的收藏添加一个Eloquent模型,您有一些选择:
在Laravel 5中,您可以从帮手中受益
$c = collect(new Post);
Run Code Online (Sandbox Code Playgroud)
要么
$c = collect();
$c->add(new Post);
Run Code Online (Sandbox Code Playgroud)
老Laravel 4答案
$c = new \Illuminate\Database\Eloquent\Collection;
Run Code Online (Sandbox Code Playgroud)
然后就可以了
$c->add(new Post);
Run Code Online (Sandbox Code Playgroud)
或者你可以使用make:
$c = Collection::make(new Post);
Run Code Online (Sandbox Code Playgroud)
Gok*_*oks 11
从Laravel 5.开始,我使用全局函数 collect()
$collection = collect([]); // initialize an empty array [] inside to start empty collection
Run Code Online (Sandbox Code Playgroud)
这个语法非常干净,如果你不想要数字索引,你也可以添加偏移量,如下所示:
$collection->offsetSet('foo', $foo_data); // similar to add function but with
$collection->offsetSet('bar', $bar_data); // an assigned index
Run Code Online (Sandbox Code Playgroud)
小智 7
我实际上发现使用newCollection()更能证明未来......
例子:
$collection = (new Post)->newCollection();
Run Code Online (Sandbox Code Playgroud)
这样,如果您决定在稍后阶段为您的模型创建自己的集合类(就像我已经做过几次一样),那么重构代码会容易得多,因为您只需覆盖newCollection()模型中的函数
这可能与原来的问题无关,但由于它是谷歌搜索中的第一个链接之一,我发现这对像我这样正在寻找如何创建空集合的人很有帮助。
如果你想手动创建一个新的空集合,你可以使用collect如下的辅助方法:
$new_empty_collection = collect();
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置找到这个助手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);
}
}
Run Code Online (Sandbox Code Playgroud)
只是为了添加到已接受的答案,您还可以在 config/app.php
'aliases' => array(
...
'Collection' => Illuminate\Database\Eloquent\Collection::class,
Run Code Online (Sandbox Code Playgroud)
然后你只需要做
$c = new Collection;
Run Code Online (Sandbox Code Playgroud)
我正在使用这种方式:
$coll = new Collection();
$coll->name = 'name';
$coll->value = 'value';
$coll->description = 'description';
Run Code Online (Sandbox Code Playgroud)
并将其用作普通集合
dd($coll->名称);
| 归档时间: |
|
| 查看次数: |
61085 次 |
| 最近记录: |