2017-08-05 101 views
1

这里是我的表结构:如何获得评论作者的姓名?

-- users 
+----+-------+ 
| id | name | 
+----+-------+ 
| 1 | John | 
| 2 | Jack | 
| 3 | Peter | 
+----+-------+ 

-- posts 
+----+---------+----------------------+-----------+ 
| id | title |   body   | author_id | 
+----+---------+----------------------+-----------| 
| 1 | title1 | somthing    | 2   | 
| 2 | title2 | whatever    | 1   | 
| 3 | title3 | anything    | 3   | 
+----+---------+----------------------+-----------+ 

-- comments 
+----+-----------------+---------+-----------+ 
| id |  message  | post_id | author_id | 
+----+-----------------+---------+-----------+ 
| 1 | my message  | 3  | 2   | 
| 2 | whatever  | 1  | 3   | 
+----+-----------------+---------+-----------+ 

现在我想其所有评论一个职位。这里是我的代码:

$post= Posts::orderBy('id', 'DESC')->where('id', $request->id)->first(); 
    $comments = $post->comments; 

注意到我在User模型这种关系:

public function comments() 
{ 
    return $this->hasMany('App\Comments','post_id', 'id')->orderBy('id'); 
} 

什么是我的问题吗?我也想获得评论作者的名字。我的意思是撰写评论的人的姓名。无论如何,我如何才能在现有的关系上建立关系?

注意:我可以通过生JOIN做到这一点。但我想知道我怎么能通过Laravel关系做到这一点?

回答

5

为什么你定义一个task_id关系?

public function comments() 
{ 
    return $this->hasMany('App\Comments','author_id', 'id'); 
} 

和评论模型:

/** 
* comments belongs to a user. 
*/ 
public function user() 
{ 
    return $this->belongsTo('App\User', 'author_id', 'id'); 
} 

现在你可以得到的意见

User::where("id",$userId)->with("comments")->orderBy('id', 'DESC')->get(); 

,如果你想获得职位所有评论的用户

在用户模型

你应该为后期模型定义这样的关系。

posts模型

定义的关系:

public function comments() 
{ 
    return $this->hasMany('App\Comments','post_id', 'id'); 
} 

和评论模型:

/** 
* comments belongs to a post. 
*/ 
public function post() 
{ 
    return $this->belongsTo('App\Posts', 'post_id', 'id'); 
} 
现在

Posts::where("id",$postId)->with("comments")->orderBy('id', 'DESC')->get(); 
+0

抱歉'task_id',这是一个错字,eidted。 –

+0

thx,upvote ..! –

+0

只是一个问题,是不是有其他方式而不是'with()'? –

2

您可以加入两个表这样

DB::table('comments') 
    ->join('users', function ($join) { 
    $join->on('comments.author_id', '=', 'users.id'); 
    }) 
    ->get(); 

https://laravel.com/docs/5.4/queries#joins

+0

THX,给予好评..! –