【问题标题】:Adding new property to Eloquent Collection向 Eloquent Collection 添加新属性
【发布时间】:2018-05-02 01:02:35
【问题描述】:

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

我需要的是这样的:

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

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

探索文档和 SO,我发现了 putprependsetAttribute 方法。

$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;

有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

    我认为你在这里混合了 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'];
    

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

    【讨论】:

    • 感谢您的回答。好的,laravel 文档告诉我们,像 'all' 或 'get' 这样的查询会返回 Illuminate\Database\Eloquent\Collection 的实例。那么setAttribute 方法不应该可用吗?并且我更新了“使用put方法”的例子。
    • 不,setAttribute 可用于单个模型,并且您不要在任何地方使用getall 来获取模型。如果您想收集可以使用的模型:$text = Text::where('id', 1)->get();,现在您在$text[0] 中有第一个模型,但显然当您通过 id 查找时,收集结果没有任何意义,因为您只有一个元素使用此 ID。
    • 明白了我错过的重点。接受你的回答。感谢您的努力。
    猜你喜欢
    • 2018-02-25
    • 2016-06-02
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    相关资源
    最近更新 更多