简体   繁体   English

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

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

I am using laravel eloquent and I made models (User,Post,Comment) 我使用laravel雄辩并制作了模型(User,Post,Comment)

the relaitions is 的关系是

User model 用户模型

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

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

Post model 发布模型

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

Comment model 评论模型

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

I Want to return all users and each user has an object of his posts and each post of those has an object of all comments 我想返回所有用户,每个用户都有他的帖子的对象,而这些用户的每个帖子都有所有评论的对象

I have this query 我有这个查询

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

it returns objects of users and each user have object of his posts, but no comments object 它返回用户的对象,每个用户都有其帖子的对象,但没有评论对象

now the problem is 现在的问题是

in php, eg I can return user[0]->posts[0]->coments() and it return the comments 在PHP中,例如我可以return user[0]->posts[0]->coments()并返回注释

but I can not see this comments in javascript or mobile phones as API it returns "try to get property of non object" 但我在JavaScript或手机中看不到此注释,因为它返回“试图获取非对象的属性”的 API

so .. I want to use the comments in js or API 所以.. 我想在js或API中使用注释

I can get the comments using for loop but I looking for better solution 我可以使用for循环获取评论,但我正在寻找更好的解决方案

You can do it like this: 您可以这样做:

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

Hope this helps! 希望这可以帮助!

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

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