繁体   English   中英

返回所有用户每个用户的帖子和每个帖子的评论laravel

[英]return all users each user with posts and each post with comments laravel

我使用laravel雄辩并制作了模型(User,Post,Comment)

的关系是

用户模型

public function posts(){
    return $this->hasMany('App\Post');
}

public function comments(){
    return $this->hasMany('App\Comment');
}

发布模型

public function comments()
{
    return $this->hasMany('App\Comment');
}
public function user()
{
    return $this->belongsTo('App\User');
}

评论模型

public function post()
{
    return $this->belongsTo('App\Post');
}

我想返回所有用户,每个用户都有他的帖子的对象,而这些用户的每个帖子都有所有评论的对象

我有这个查询

$users = \App\User::with('posts')->\get();
return $users;

它返回用户的对象,每个用户都有其帖子的对象,但没有评论对象

现在的问题是

在PHP中,例如我可以return user[0]->posts[0]->coments()并返回注释

但我在JavaScript或手机中看不到此注释,因为它返回“试图获取非对象的属性”的 API

所以.. 我想在js或API中使用注释

我可以使用for循环获取评论,但我正在寻找更好的解决方案

您可以这样做:

$users = \App\User::with('posts', 'posts.comments')->get();
return $users;

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM