如何获得所有相关帖子?

时间:2018-04-10 08:12:17

标签: laravel join relation

这是我的表结构:

// tickets
+----+------------+----------------------+--------+---------+
| id |  subject   |        content       | closed | user_id |
+----+------------+----------------------+--------+---------+
| 1  | subject1   | question1            | 0      | 123     |
+----+------------+----------------------+--------+---------+

// answers
+----+----------------------+---------+-----------+
| id |        content       | user_id | ticket_id |
+----+----------------------+---------+-----------+
| 1  | answer1              | 123     | 1         |
| 2  | answer2              | 456     | 1         |
+----+----------------------+---------+-----------+

现在我需要获得一张票据及其所有答案。我可以使用纯SQL这样做:

SELECT t.*, a.*
FROM tickets t
LEFT JOIN answers a
ON t.id = a.ticket_id
WHERE t.id = ?

现在我正在使用Laravel,我希望使用with() class (但不确定是否可能)来实现。知道我应该在模型中做出哪些改变吗?

注意到我可以在Laravel中获得这样一张票:

$ticket = Tickets::where('id', $request->id)->get();

1 个答案:

答案 0 :(得分:3)

首先在Tickets模型类中建立hasMany()关系。

public function answers()
{
    return $this->hasMany(Answers::class, 'ticket_id', 'id');
}

然后在您的控制器查询中

$tickets = Tickets::with('answers')->where('id', $request->id)->get();