【问题标题】:Creating a new empty property to an Eloquent collection为 Eloquent 集合创建一个新的空属性
【发布时间】:2019-04-22 20:35:02
【问题描述】:

我有一个集合,我循环浏览并尝试添加一个具有空值的新属性 suffix

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

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

目前,每个$author 都有两个属性,

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

如果我在第一次迭代后dd($author);,我会得到

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

但如果我在两个foreach 循环之后dd($results);,它不会坚持添加空的suffix 属性。

如何更改集合以保留 suffix 属性?

【问题讨论】:

  • 你能把EloTable型号代码贴出来吗?

标签: php laravel eloquent


【解决方案1】:

如果您没有在原始$results 中加载datadata.authors,那么稍后调用$results->data->authors 或类似的东西将重新查询数据库,提取authors 的新副本没有被修改。

只需将$results 更改为:

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

【讨论】:

    【解决方案2】:

    您可以像这样将属性附加到模型:

    型号:

    protected $appends = ['suffix'];
    
    public function getSuffixAttribute()
    {
        return null;  
    }
    

    文档:

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

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

    【讨论】:

    • 追加的问题是后缀会作为属性添加到每个文档的主层。我不希望它是$result->suffix,我希望它是$result->data->authors->SUFFIX HERE,名字和姓氏在哪里。有什么办法吗?
    猜你喜欢
    • 2014-06-29
    • 2017-04-29
    • 2018-02-25
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2022-10-14
    • 2016-05-15
    相关资源
    最近更新 更多