I am trying to migrate some Raw SQL to an Eloquent (or Query Builder) scope on my model. My Parts history table looks like this:
+----+---------+--------+------------+
| id | part_id | status | created_at |
+----+---------+--------+------------+
| 1 | 1 | 1 | ... |
| 2 | 1 | 2 | ... |
| 3 | 2 | 1 | ... |
| 4 | 1 | 2 | ... |
| 5 | 2 | 2 | ... |
| 6 | 1 | 3 | ... |
Notice the same part_id can have multiple entries where the status is the same.
At the moment I use the following to select the latest status:
$part = Part::leftjoin( DB::raw("
(SELECT t1.part_id, ph.status, t1.part_status_at
FROM (
SELECT part_id, max(created_at) part_status_at
FROM part_histories
GROUP BY part_id) t1
JOIN part_histories ph ON ph.part_id = t1.part_id AND t1.part_status_at = ph.created_at) as t2
)", 't2.part_id', '=', 'parts.id')->where( ... )
I am trying to make a scope on the parts model out of this, so far I have this:
public function scopeWithLatestStatus($query)
{
return $query->join(DB::raw('part_histories ph'), function ($join) {
$join->on('ph.part_id', '=', 't1.id')->on('t1.part_status_at', '=', 'ph.created_at');
})
->from(DB::raw('(select part_id as id, max(created_at) part_status_at from part_histories GROUP BY part_id) t1'))
->select('t1.id', 'ph.part_status', 't1.part_status_at');
}
which is part way there (but still using some raw SQL), I just can't figure out the rest