我怎样才能得到所有相关的post?

How can I get a post with all related ones?

这是我的 table 结构:

// 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();

首先在您的 Tickets 模型中建立 hasMany() 关系 class。

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

然后在你的控制器查询

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