【发布时间】:2018-01-13 02:09:30
【问题描述】:
这是我的表结构:
-- 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 |
+----+-----------------+---------+-----------+
现在我想获得 一个包含所有 cmets 的帖子。这是我的代码:
$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');
}
我的问题是什么?我也想知道 cmets 的作者姓名。我的意思是写评论的人的名字。无论如何,我怎样才能在现有关系上建立关系?
注意:我可以通过原始JOIN 做到这一点。但我想知道如何通过 Laravel 关系做到这一点?
【问题讨论】:
标签: php laravel polymorphic-associations