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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 12:02:33