简体   繁体   中英

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.

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

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

If I dd($author); after the first iteration, I will get

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

But if I dd($results); after the two foreach loops, it will not persist the addition of the empty suffix properties.

How can I change the collection to persist the suffix property?

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-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.

Just change $results to :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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