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

Laravel 10中如何在Eloquent请求同时指定字段与关联查询?

解决Laravel指定主表字段后关联模型为null的问题

问题核心是你在select中遗漏了关联所需的外键字段,Eloquent需要通过这个字段去匹配关联的Creator模型,没选的话就无法建立关联,自然返回null,也不会触发关联查询。

解决方法

  1. 在主表select中加入外键字段
    假设Post表关联Creator的外键是creator_id,把它加入select列表即可:
$postList = Post
    ::orderBy('created_at', 'desc')
    ->with('creator')
    ->select('id', 'title', 'slug', 'published', 'created_at', 'creator_id')
    ->get();
  1. 可选:精简关联模型的查询字段
    如果不想查询Creator表的所有字段,可以在with中进一步指定关联模型要查询的字段,但必须包含Creator表的主键(默认是id),否则Eloquent无法匹配关联:
$postList = Post
    ::orderBy('created_at', 'desc')
    ->with(['creator' => function ($query) {
        $query->select('id', 'name'); // 只获取需要的字段
    }])
    ->select('id', 'title', 'slug', 'published', 'created_at', 'creator_id')
    ->get();

注意事项

如果你的Post模型中定义creator关联时用了自定义外键(不是默认的creator_id),比如:

public function creator()
{
    return $this->belongsTo(Creator::class, 'custom_creator_id');
}

那就要把custom_creator_id加入主表的select列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:42:18