返回所有用户的每个用户的帖子和每个帖子的评论laravel
I am using laravel eloquent and I made models (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, e.g. I can return user[0]->posts[0]->coments()
and it return the comments
but I can not see this comments in javascript or mobile phones as API it returns "try to get property of non object"
so .. I want to use the comments in js or API
I can get the comments using for loop but I looking for better solution
我正在使用laravel eloquent并制作模型(用户,帖子,评论) p>
关联是 p>
用户 strong>模型 p>
发布 strong>模型 p>
评论 strong>模型 p>
我想返回所有用户,每个用户都有自己帖子的对象,每个帖子都有一个对象 所有评论 p>
我有这个查询 p>
它返回 用户和每个用户的对象都有他的帖子的对象,但没有评论对象 p>
现在问题是 p>
在php中,例如 我可以 但是我看不到这个 在javascript或手机中评论API
it返回“尝试获取非对象属性” em> p>
所以.. 我想使用评论 在js或API strong> p>
我可以使用for循环获取注释,但我寻找更好的解决方案 p>
div>
公共职能帖子(){
返回$ this-> hasMany('App \ Post');
}
公共函数comments(){
返回$ this-> hasMany('App \ Comment');
}
code > pre>
公共职能评论()
{
返回$ this-&gt ; hasMany('App \ Comment');
}
公共函数user()
{
返回$ this-> belongsTo('App \ User');
}
code> pre>
公共职能帖子()
{
返回$ this-> belongsTo( 'app \ Post');
}
code> pre>
$ users = \ App \ User :: with('posts') - > \ get();
return $ users;
code> pre>
返回用户[0] - > posts [0] - > coments() code>
并返回评论 p>
You can do it like this:
$users = \App\User::with('posts', 'posts.comments')->get();
return $users;
Hope this helps!