如何在不循环每个项目内部的情况下循环集合



我有一个集合。对于每个项目,我想添加一个新属性 [users]。当我使用 map 函数循环收集时,甚至 foreach,我注意到代码在每个项目中循环。因此,从收藏品中读取每个贡品。请看下面这个

   Log $myCollection: 
    local.INFO: IlluminateSupportCollection Object
    (
        [items:protected] => Array
            (
                [0] => Array
                    (
                        [id] => 6
                        [name] => AAAAA
                        [code] => D2
                        [component_id] => 5
                    )
                [1] => Array
                    (
                        [id] => 7
                        [name] => BBBB
                        [code] => D1
                        [component_id] => 5
                    )
                [2] => Array
                    (
                        [id] => 47
                        [name] => CCCC
                        [code] => CR7
                        [component_id] => 3
                    )
                [3] => Array
                    (
                        [id] => 48
                        [name] => DDDD
                        [code] => CJ9
                        [component_id] => 3
                    )
            )
    )

    $myCollection->map(function ($item) use($users, $role) {
        $item = Site::findOrFail($item);
        $item->users = $users;
        return $item;
    });

我得到 : SQLSTATE[22P02]:无效的文本表示形式:7 错误:整数"AAAA"的输入语法无效。我认为这是因为代码循环访问了 myCollection 每个项目的名称。

请问我该如何解决它?谢谢

$item包含集合的每个对象,因此应使用适当的键。

$myCollection->map(function ($item) use($users, $role) {
   $item = Site::findOrFail($item->id); // or $item['id']
   $item->users = $users;
   return $item;
});

其实现在我看得更好了,你根本不需要再次找到这个项目。所以在你的闭包中,只有这两行就足够了。

$item->users = $users;
return $item;

最新更新