2017-08-05 105 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,給予好評..! –