Laravel API获取评论及回复遇错误:Property [id]不存在于Eloquent构建器实例
解决「Property [id] does not exist on the Eloquent builder instance」错误
这个错误的根源很明确:你在资源里传递给CommentCollection的不是查询结果集合,而是未执行的Eloquent查询构建器实例。咱们一步步来修复:
1. 直接修复当前代码的错误
在你的GetPostsSinglePageData资源的toArray方法中,Comment::select('*')->where('post_id',$this->id)只是创建了一个查询构建器,并没有执行查询返回数据集合。你需要加上->get()来执行查询,把构建器转为Eloquent集合:
// 原错误代码 'comments'=> new CommentCollection(Comment::select('*')->where('post_id',$this->id)), // 修改后代码 'comments'=> new CommentCollection(Comment::where('post_id',$this->id)->get()),
(注:select('*')可以省略,Eloquent默认会查询所有字段)
2. 用Laravel关联优化代码(更优雅的方案)
其实Laravel的Eloquent关联更适合这种关联数据查询场景,不仅代码更简洁,还能避免N+1查询的性能问题。
第一步:在Post模型中定义评论关联
// app/Models/Post.php public function comments() { return $this->hasMany(Comment::class); }
第二步:在资源中直接调用关联关系
这样你就不用手动写where条件了,直接通过模型关联获取评论:
// GetPostsSinglePageData资源的toArray方法 'comments'=> new CommentCollection($this->comments),
第三步:预加载关联避免N+1查询
在控制器查询Post时,提前预加载comments关联,减少数据库查询次数:
// 控制器代码修改 $post = Post::where('id',$post_id) ->where('status', '=', 1) ->with('comments') // 预加载评论关联 ->get();
额外的小优化
你的CommentCollection里查询用户的代码也可以用关联优化:
- 在Comment模型中定义用户关联:
// app/Models/Comment.php public function user() { return $this->belongsTo(User::class); }
- 在CommentCollection中直接使用关联:
// 这里如果UserInfoCollection是单资源集合,建议改用单个资源类 'users'=> new UserInfoCollection(collect([$this->user])),
同时记得在控制器预加载时加上with('comments.user'),进一步优化查询性能。
这样改完之后,错误就会消失,代码也更符合Laravel的最佳实践啦~
内容的提问来源于stack exchange,提问作者Zia Yamin
相关产品推荐
相关产品推荐

