You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel:如何重新赋值集合内模型的数组属性?或分组关联数组?

问题

我获取了包含items关联的Listt模型集合,需要将每个Listt实例的items按id分组。但尝试重新赋值$list->items时均无效果,而重新赋值$list->name却能正常生效,推测问题出在数组类型的属性上。请问该如何实现集合内模型数组属性的重新赋值?

$lists = Listt::with('items')->get();
$newLists = $lists->map(function(Listt $list) {

    // $list->items = $list->items->groupBy('id'); // this is what I want, it doesn't work
    // $list->items = []; // this doesn't work either
    // $list['items'] = []; // nope
    // $list->items = new Collection(); // nope
    $list->items = collect([... $list->items])->groupBy('id');// nope

    $list->name = 'test'; //this works, so the problem is arrays <----

    return $list;
});
return $newLists;

/* transform doesn't work */
// $lists->transform(function(Listt $list) {
    //... 
// });
// return $lists;

/* this, from a similar question, doesn't work either, besides I don't understand it and it doesn't use collection methods... */
// foreach($lists as &$list){
//    $list['items'] = [];
//    unset($list);
// }
// return $lists;
解决方案

问题核心是items是Laravel模型的关联关系属性,而非普通模型属性,直接赋值无法覆盖已加载的关联数据,必须使用模型内置的setRelation方法来更新关联内容。

正确实现代码如下:

$lists = Listt::with('items')->get();
$newLists = $lists->map(function(Listt $list) {
    // 对关联的items按id分组
    $groupedItems = $list->items->groupBy('id');
    // 使用setRelation更新关联数据
    $list->setRelation('items', $groupedItems);

    $list->name = 'test'; // 普通属性赋值不受影响

    return $list;
});

return $newLists;

额外说明

  • setRelation方法会正确更新模型内部维护的关联数据容器,确保修改后的关联能被正常序列化和访问,这是直接赋值关联属性做不到的。
  • 若需直接修改原集合而非生成新集合,可替换map为transform,逻辑完全一致:
$lists->transform(function(Listt $list) {
    $groupedItems = $list->items->groupBy('id');
    $list->setRelation('items', $groupedItems);
    $list->name = 'test';
    return $list;
});

return $lists;

内容的提问来源于stack exchange,提问作者user17169022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:15:56