laravel - 向 Eloquent Collection 添加新属性

标签 laravel laravel-5 eloquent laravel-5.2 laravel-collection

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

我需要的是这样的:

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

并通过,$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

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


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

有什么帮助吗?

最佳答案

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

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

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

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

您正在服用 c而你没有这样的元素。您应该做的是获取位于 a 的元素关键是这样的:
echo $collection->get('a');

或者像这样使用数组访问:
echo $collection['a'];

还要注意没有 setAttribute Collection 上的方法。有setAttribute Eloquent 模型上的方法。

关于laravel - 向 Eloquent Collection 添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364421/

相关文章:

laravel - 如何通过分页获取 Laravel Eloquent 中的特定列?

laravel - 模型的正常方法被属性错误

php - 如何在 Laravel 中使用紧凑型发送成功消息

javascript - 如何获取并提交购物车中选中的商品?

php - 使用 Laravel 框架包含 PHP 文件

json - Laravel json 响应 : response()->json() or $var->toJson()

laravel - 无法检测回调是否源自 Laravel Socialite 中的提供者

Laravel 5.1 多重认证

laravel - 到达数据透视表字段 Laravel 5.5

php - 无法在后台和守护进程中运行 artisan redis :subscribe command as service,