Laravel BelongsToMany多对多关联下如何选取关联表的指定字段?
解决方案
实现方式有两种,按需选择即可:
方案1:仅当前查询生效(推荐,不影响其他业务调用关联)
直接在现有查询链上补充select方法指定posts表的返回字段,必须保留id字段,否则后续的关联预加载、统计查询会因为缺少主键无法正常执行。
完整代码示例:
$posts = $this->section1->posts() ->select('id', 'title') // 新增此行指定需要返回的post字段 ->with([ 'survey' => function ($query) { $query->withCount('totalSurveys'); }, 'survey.surveyOptions', 'survey.totalSurveys.survey_option.color', 'image', 'categories:id,name,slug', ]) ->withCount('comments') ->where('status', Post::PUBLICADO) ->orderBy('order', 'ASC') ->get();
方案2:全局关联默认生效(所有调用该关联的场景默认只返回id和title)
你修改关联定义的思路是可行的,没生效大概率是缓存或者其他查询逻辑覆盖了字段配置,调整关联定义如下即可:
public function posts() { // 显式加表名前缀避免多表关联查询时字段冲突,必须保留id作为关联匹配主键 return $this->belongsToMany(Post::class)->select('posts.id', 'posts.title'); }
注意:如果你的排序字段
order存储在多对多的中间表中,需要额外调用withPivot('order')加载中间表字段,否则排序逻辑会报错。
内容的提问来源于stack exchange,提问作者Alberto
相关产品推荐
相关产品推荐

