【问题标题】:transform on a laravel collection is not changing an attributelaravel 集合上的转换不会改变属性
【发布时间】:2021-11-20 09:13:27
【问题描述】:

在以下代码中,“liked_by_me”列保持不变,但添加了“newAttr”列。

    $commentList->transform(function($item, $key) {
        $item->liked_by_me == null ? $item->liked_by_me = false : $item->liked_by_me = true;
        $item->liked_by_me == null ? $item->newAttr = false : $item->newAttr = true;
        return $item;
    });

$commentList 集合是使用 cmets 表的标准模型从数据库读取的结果。我正在运行 Laravel 8

似乎无法更改结果集合的行中的现有属性,但添加新属性是可行的。我还尝试了使用 ->map() 和 ->each 的各种迭代,似乎没有什么可以让我更改从数据库中检索到的集合中的行的属性。

【问题讨论】:

    标签: laravel collections transform


    【解决方案1】:

    使用地图功能,它对我有用

    $commentList->map(function($item){
      //DO YOUR STUFF HERE
    
      return $item;
    

    });

    【讨论】:

      【解决方案2】:

      不要将空值与“==”进行比较。请改用 is_null() 函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-27
        • 1970-01-01
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        • 2020-07-11
        • 2019-07-10
        相关资源
        最近更新 更多