如何从关系中检索数据?

时间:2015-09-04 06:46:13

标签: php

发布模型

MailItem.Display

评论模型

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');
    }


   }  

现在我的问题是如何通过注释用户名访问所有属于帖子的评论 提前谢谢

3 个答案:

答案 0 :(得分:1)

我认为你的问题很容易通过hasmanythrough关系来解决(检查http://laravel.com/docs/5.1/eloquent-relationships)。

答案 1 :(得分: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(); 

答案 2 :(得分:1)

您可以对评论关系进行查询,如下所示:

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

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