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
相关产品推荐
相关产品推荐

