我是Laravel的新手,我正在使用Laravel5.2,我想获得用户特定帖子的所有评论。我的表格是这样的:
User
-----
id
public function posts() {
$this->hasMany( 'App'Posts' )
}
Post
------
id
user_id
public function user() {
$this->belongsTo( 'App'User' )
}
public function comments() {
$this->hasMany( 'App'Comment' )
}
Comments
----------
id
post_id
public function post() {
$this->belongsTo( 'App'Post' )
}
现在我想要的是获取特定用户的所有帖子,例如登录用户。我可以通过很长的方式获得所有评论,例如:
$comments = [];
foreach( Auth::user()->posts as $post) {
foreach( $post->comments as $comment )
{
$comments[] = $comment->title
}
}
但是我想知道如何在不仅使用关系进行这些循环的情况下获取评论。提前谢谢。
您可以将现有用户对象的关系加倍:
$posts = 'Auth::user()->posts()->with('comments')->get();
它应该适用于所有级别。
在我的项目中,我有有客户的组织,有一个指向治疗师的链接表,都是多个,这有效:
Organization::find(1)->clients()->with('therapists')->get();
所以你的案子也应该有效。让我知道。
本质上,
您希望使用with()
和点表示法来加载数据,如下所示:
$user = User::with('posts.comments')->find(Auth::user()->id);
如果你只是想要评论,你可以做:
$user = User::with('comments')->find(Auth::user()->id);
$comments = $user->comments();