简体   繁体   English

为Eloquent集合创建一个新的空属性

[英]Creating a new empty property to an Eloquent collection

I have a collection that I cycle through and attempt to add a new property suffix with an empty values. 我有一个循环浏览的集合,并尝试添加具有空值的新属性suffix

    $results = Models\EloTable
        ::hydrate((array) $query)
        ->load(
            'extraction',
            'reference'
        );

    foreach ($results as $result) {
        foreach ($result->data->authors as $author) {
            $author->suffix = '';
        }
    }

Currently, every $author has two properties, 目前,每个$author都有两个属性,

{
    lastName: "Lastname",
    firstName: "Firstname"
}

If I dd($author); 如果我dd($author); after the first iteration, I will get 第一次迭代后,我会得到

{
    lastName: "Lastname",
    firstName: "Firstname",
    suffix: ""
}

But if I dd($results); 但是如果我dd($results); after the two foreach loops, it will not persist the addition of the empty suffix properties. 在两个foreach循环之后,它将不会持续添加空suffix属性。

How can I change the collection to persist the suffix property? 如何更改集合以保留suffix属性?

You can append an attribute to a model like this: 您可以将属性附加到模型中,如下所示:

Model: 模型:

protected $appends = ['suffix'];

public function getSuffixAttribute()
{
    return null;  
}

Documentation: 文档:

https://laravel.com/docs/5.8/eloquent-mutators https://laravel.com/docs/5.8/eloquent-mutators

https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json

If you don't load data and data.authors in your original $results then calling $results->data->authors or something similar later down the line will re-query the database, pulling a fresh copy of authors that hasn't been modified. 如果您不使用原始的$results加载datadata.authors在随后的行中调用$results->data->authors data.authors $results->data->authors或类似的内容将重新查询数据库,并提取一个尚未复制的authors的新副本。被修改。

Just change $results to : 只需将$results更改为:

$results = Models\EloTable
        ::hydrate((array) $query)
        ->load(
            'extraction',
            'reference',
            'data',
            'data.authors',
        );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM