laravel 向 Eloquent Collection 添加新属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47364421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:58:52  来源:igfitidea点击:

Adding new property to Eloquent Collection

laravellaravel-5eloquentlaravel-5.2laravel-collection

提问by MASh

Trying to add new property to existing collection and access that.

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

What I need is something like:

我需要的是这样的:

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

And access the user via, $text->user.

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

Exploring on documentation and SO, I found put, prepend, setAttributemethods to do that.

探索对文档和SO,我发现putprependsetAttribute的方法来做到这一点。

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

Again,

再次,

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

And

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

Any help?

有什么帮助吗?

采纳答案by Marcin Nabia?ek

I think you mix here Eloquent collection with Support collection. Also notice when you are using:

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

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

you don't have here any collection but only single object.

您在这里没有任何集合,而只有单个对象。

But let's look at:

但让我们看看:

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

You are taking cand you don't have such element. What you should do is taking element that is at akey like this:

你正在服用c而你没有这样的元素。你应该做的是a像这样获取关键的元素:

echo $collection->get('a');

or alternatively using array access like this:

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

echo $collection['a'];

Also notice there is no setAttributemethod on Collection. There is setAttributemethod on Eloquent model.

还要注意setAttributeCollection 上没有方法。setAttributeEloquent 模型上有方法。