向 Eloquent Collection 添加新属性

MAS*_*ASh 7 laravel eloquent laravel-5 laravel-collection

尝试将新属性添加到现有集合并访问它。

我需要的是这样的:

$text = Text::find(1);  //Text model has properties- id,title,body,timestamps
$text->user = $user;
Run Code Online (Sandbox Code Playgroud)

并通过访问用户,$text->user.

探索文档和 SO,我找到了put, prepend,setAttribute方法来做到这一点。

$collection = collect();
$collection->put('a',1);
$collection->put('c',2);
echo $collection->c; //Error: Undefined property: Illuminate\Support\Collection::$c
Run Code Online (Sandbox Code Playgroud)

再次,

$collection = collect();
$collection->prepend(1,'t');
echo $collection->t = 5; //Error: Undefined property: Illuminate\Support\Collection::$t
Run Code Online (Sandbox Code Playgroud)

$collection = collect();
$collection->setAttribute('c',99); // Error: undefined method setAttribute
echo $collection->c;
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

Mar*_*łek 7

我认为你在这里将 Eloquent 集合与 Support 集合混合在一起。使用时还要注意:

$text = Text::find(1);  //Text model has properties- id,title,body,timestamps
$text->user = $user;
Run Code Online (Sandbox Code Playgroud)

你这里没有任何集合,只有单个对象。

但让我们看看:

$collection = collect();
$collection->put('a',1);
echo $collection->c; //Error: Undefined property: Illuminate\Support\Collection::$c
Run Code Online (Sandbox Code Playgroud)

你正在服用c,但你没有这样的元素。你应该做的是采取a这样的关键元素:

echo $collection->get('a');
Run Code Online (Sandbox Code Playgroud)

或者使用像这样的数组访问:

echo $collection['a'];
Run Code Online (Sandbox Code Playgroud)

setAttribute另请注意, Collection 上没有方法。Eloquent 模型上有setAttribute方法。

  • 不,setAttribute 可用于单个模型,并且您不能在此处使用“get”或“all”来获取模型。如果你想收集模型,你可以使用: `$text = Text::where('id', 1)->get();` 现在你在 `$text[0]` 中有第一个模型,但显然当您通过 id 查找时,收集结果没有任何意义,因为您只有具有此 id 的单个元素。 (2认同)