2015-09-04 63 views
2

邮政型号如何从关系中检索数据?

class Post extends Model 
{ 


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

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

评论模型

class Comment extends Model 
    { 

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


    } 

用户模型

class User extends Model 
{ 


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

现在我的问题是我怎么可以访问属于后所有评论评论ed用户名 谢谢你提前

+0

仅具有用户名你只能够得到所有评论所有帖子归特定用户所有,为此你可以使用hasManyThrough关系 – zakius

+0

@ zakius.thank你的评论。你发布你的答案 – iCoders

+0

试试这个'user :: with('post.comment') - > get()' – mdamia

回答

1

尝试此操作,它将返回所有包含评论的帖子,并为所选用户返回包含作者的帖子。

$data = User::with('post.comment') 
     -> with('post.author') 
     -> Where('id',$user_id) 
     -> first(); 

这将获取与作者的帖子和帖子发表评论与发表评论的用户。 假设你的模型,这种方式设置,

Post belongs to an Author, 
Author has many Post, 
Post has many Comment 
Comment belongs to a Post 
Comment belongs to a User 
User has many Comment. 

$posts = Post::with('author') -> with('comment.user') -> get(); 
+0

我的要求是。我需要显示帖子与帖子autoe的名字,并与评论属于那个帖子与评论username.if你看到我的表结构。存储评论用户ID意味着Forign键 – iCoders

+0

@vision改变你的查询,我会更新。 – mdamia

+0

谢谢。我会尝试 – iCoders

1

你可以做评论的关系查询,如下所示:

$post_id = 7; 
$username = 'username'; 

$comments = Comment::where('post_id', $post_id)->whereHas('user', function($q) use($username) { 
    $q->where('username', $username); 
})->get(); 
+0

@ Iamzozo.thank你.ii会尝试 – iCoders