Laravel Eloquent:如何让belongsToMany返回字符串数组而非对象数组
实现将关联返回结果转为指定字段数组的方法
可以通过Eloquent的多种方式实现需求,以下是几种实用方案:
方案一:关联查询时指定字段+集合提取
在关联预加载时仅选择需要的字段(必须包含关联外键,否则Eloquent无法完成模型匹配),再用集合的pluck方法提取目标字段转为数组:
$show = Shows::where('id', 1)->with(['draft_types' => function ($query) { $query->select('draft_type_id', 'type'); }])->first(); // 提取type字段为字符串数组 $typeArray = $show->draft_types->pluck('type')->toArray();
方案二:模型中定义访问器
如果需要频繁获取该数组,可以在Show模型中定义访问器,自动处理关联数据:
// Show模型内添加 public function getDraftTypeListAttribute() { return $this->draft_types->pluck('type')->toArray(); }
使用时直接访问自定义属性:
$show = Shows::where('id', 1)->with('draft_types')->first(); $typeArray = $show->draft_type_list;
方案三:自定义关联简化查询
可以通过hasManyThrough定义一个直接关联到draft_types的简化关联,再提取字段:
// Show模型内添加 public function draftTypeList() { return $this->hasManyThrough( DraftTypes::class, ShowDraftTypes::class, 'show_id', 'id', 'id', 'draft_type_id' )->select('type'); }
查询时直接获取并转换:
$typeArray = Shows::where('id', 1)->with('draftTypeList')->first()->draftTypeList->pluck('type')->toArray();
内容的提问来源于stack exchange,提问作者pbrune
相关产品推荐
相关产品推荐

