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
Adding new property to Eloquent 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
, setAttribute
methods to do that.
探索对文档和SO,我发现put
,prepend
,setAttribute
的方法来做到这一点。
$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 c
and you don't have such element. What you should do is taking element that is at a
key like this:
你正在服用c
而你没有这样的元素。你应该做的是a
像这样获取关键的元素:
echo $collection->get('a');
or alternatively using array access like this:
或者像这样使用数组访问:
echo $collection['a'];
Also notice there is no setAttribute
method on Collection. There is setAttribute
method on Eloquent model.
还要注意setAttribute
Collection 上没有方法。setAttribute
Eloquent 模型上有方法。