这里是我的表结构:如何获得评论作者的姓名?
-- 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关系做到这一点?
抱歉'task_id',这是一个错字,eidted。 –
thx,upvote ..! –
只是一个问题,是不是有其他方式而不是'with()'? –