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

Laravel8使用with()关联查询报错Call to a member function addEagerConstraints() on null

问题分析与解决:Call to a member function addEagerConstraints() on null

核心问题出在Post模型的author()关联方法未返回关联实例:

你的Post模型中author()方法只调用了$this->belongsTo(Author::class),但没有用return返回这个关联对象,导致Laravel执行预加载with('author')时,拿到的是null,自然无法调用addEagerConstraints()方法。

修正后的Post模型代码:

class Post extends Model
{
    use HasFactory;
    public function author(){
        // 加上return返回关联实例
        return $this->belongsTo(Author::class);
    }
}

另外补充一个小建议:Author模型中的post()方法,建议命名为复数posts(),更符合Laravel的命名规范(一对多关系中,关联方法用复数形式更直观),修正后:

class Author extends Model
{
    use HasFactory;
    public function posts(){
       return $this->hasMany(Post::class);
    }
}

修正后再执行Post::with('author')->get()就能正常获取关联数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:36:29