I have a table named freight, with has many historics, with the table name freight_historic. 1:N. In this historic table i have 3 columns,the id
(primary key, auto incremented), the freight_id
and freight_statuses_id
.
A freight can have multiple historic with status, the last historic row from a specific freight determines your current status.
The freight_statuses table has some columns, ID and NAME. and some records. A small example below
+----+-----------+
| ID | NAME |
+----+-----------+
| 1 | TRAVELING |
+----+-----------+
| 2 | CANCELLED |
+----+-----------+
The freight_historics could be
+----+------------+---------------------+
| ID | FREIGHT_ID | FREIGHT_STATUSES_ID |
+----+------------+---------------------+
| 1 | 1 | 1 |
+----+------------+---------------------+
| 2 | 1 | 2 |
+----+------------+---------------------+ --> last row inserted
I tried this code to show all freights with has TRAVELING status, but a freight has 2 historics, with statuses TRAVELING and CANCELLED(WITH THE LAST RECORD INSERTED), still shows me the result.
$freight = Freight::with(['lastStatus.statusName'])->whereHas('lastStatus.statusName', function ($query) {
$query->where('name', 'TRAVELING');
})->get();
//Models
class FreightHistoric extends Model
{
public function statusName() {
return $this->belongsTo(FreightStatus::class, 'freight_statuses_id', 'id');
}
}
class Freight extends Model
{
public function lastStatus()
{
return $this->hasOne(FreightHistoric::class, 'freight_id', 'id')->latest();
}
}
This code shows all records, with 'TRAVELING` status. I want to show the freight's with' TRAVELING 'status in his historic only if its the last record.
You can use Laravel Query Builder
$latestHistoric= DB::table('freight_historics')
->latest()
->first();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.