I want to select a specific record from table a and all their latest records from table a_b that has relation with table b before a specific date. For example
Table (a)
id | name |
---|---|
1 | aa |
Table (b)
id | name |
---|---|
1 | b1 |
2 | b2 |
3 | b3 |
4 | b4 |
Table (a_b)
id | a_id | b_id | date |
---|---|---|---|
1 | 1 | 1 | 2022-09-06 |
2 | 1 | 2 | 2022-09-06 |
3 | 1 | 1 | 2022-09-07 |
4 | 1 | 2 | 2022-09-07 |
5 | 1 | 1 | 2022-09-10 |
6 | 1 | 2 | 2022-09-10 |
If I want the latest records before 2022-09-09 the Output should be
id | a_name | b_name | date |
---|---|---|---|
1 | aa | b1 | 2022-09-07 |
2 | aa | b2 | 2022-09-07 |
This is can be done using pure SQL:
select a.id,a.name,b.name,a_b.date
from a
LEFT JOIN a_b on a_b.a_id = a.id
INNER JOIN b on b.id = a_b.b_id
where a.id = 1
AND a_b.date = (
select max(a_b.date) from a
LEFT JOIN a_b on a_b.a_id = a.id
INNER JOIN b on b.id = a_b.b_id
WHERE a.id = 1 AND a_b.date < = '2022-09-09')
How can I achieve the same output using Laravel eloquent using (with)?
A::with([
'B'=> function ($query) use ($date) {
/// what should I write here
}])->get()