Laravel 8中预加载嵌套模型时如何指定包含/排除数据库字段?
关联模型仅获取指定字段的实现
场景说明
现有以下模型关联关系:
User模型:
class User { public function posts() { return $this->hasOne(Post::class); } }
Post模型:
class Post { public function comments() { return $this->hasMany(Comment::class); } }
需要实现:通过$user->post->comments仅获取Comment模型的comment_id和comment_content字段,而非所有字段。
解决方案
方案1:全局修改关联定义
直接在Post模型的comments关联中指定要查询的字段,注意必须包含关联外键(如post_id),否则Eloquent无法建立关联关系:
class Post { public function comments() { return $this->hasMany(Comment::class)->select(['comment_id', 'comment_content', 'post_id']); } }
之后调用$user->post->comments时,只会返回指定的三个字段。
方案2:动态按需指定字段
如果不需要全局修改关联,仅在单次查询中获取指定字段,可以直接在查询时添加select约束:
$user = Auth::user(); $comments = $user->post->comments()->select(['comment_id', 'comment_content', 'post_id'])->get();
或者使用预加载的方式,提前指定字段:
$user = Auth::user()->load(['post.comments' => function ($query) { $query->select(['comment_id', 'comment_content', 'post_id']); }]); $comments = $user->post->comments;
注意:关联查询必须包含外键字段(如
post_id),否则Eloquent无法匹配关联的模型数据,会返回空集合。
内容的提问来源于stack exchange,提问作者Tarek
相关产品推荐
相关产品推荐

