【发布时间】:2017-05-06 15:14:10
【问题描述】:
是否可以使用 Eloquent 进行比 1 级更深的多级关系查询?我的表是这样的:
post_cmets-> id|comment|post_id|user_id|...
post_comment_replies-> id|reply|post_comment_id|user_id|...
用户-> id|name|....
user_data-> id|头像|...
所以我想问一下,是否有可能获取 Post 的 Comments 以及所有 Replies 和用户数据使用 Eloquent 在 1 个查询中回复评论的人。
这就是我的评论模型的样子:
class PostComment extends Model{
public function replies(){
return $this->hasMany(PostCommentAwnsers::class);
}
public function user() {
return $this->belongsTo(User::class);
}
public function userInfo(){
return $this->belongsTo(UserInfo::class,'user_id','user_id');
}}
public function index($id){
$posts = Post::find($id);
$postComments = PostComment::where('post_id','=',$id)->paginate(5);
return view('post.show',[
'post' => $post,
'postComments' =>$postComments
]);
}
当我获得评论的所有用户数据时,我想获得回复者的所有用户数据。 如果这已被 awnsered 或在其他地方记录,我真的很抱歉,但我似乎无法找到这个问题的确切解决方案。
【问题讨论】:
-
您确定
user_data需要在单独的表中吗?如果是一对一的关系,你应该合并两个表。 -
是的,但它包含很多列,我只在这个项目的少数情况下使用 user_data 表,我不想调用我只需要用户 ID 的所有用户数据和名字
-
你可以使用
$user = User::where('id', '=', $id)->select('firstname', 'lastname')->get()laracasts.com/index.php/discuss/channels/eloquent/…只查询你需要的数据
标签: php laravel eloquent laravel-5.2