我有一个名为Freight的表,它具有许多历史记录,表名称为Freight_historic。 1:N在此历史表中,我有3列,id
(主键,自动递增),freight_id
和freight_statuses_id
。
货运可以具有多个历史状态,特定货运的最后一个历史行确定您当前的状态。
Freight_statuses表具有一些列,即ID和NAME。和一些记录。下面是一个小例子
+----+-----------+
| ID | NAME |
+----+-----------+
| 1 | TRAVELING |
+----+-----------+
| 2 | CANCELLED |
+----+-----------+
freight_historics可能是
+----+------------+---------------------+
| ID | FREIGHT_ID | FREIGHT_STATUSES_ID |
+----+------------+---------------------+
| 1 | 1 | 1 |
+----+------------+---------------------+
| 2 | 1 | 2 |
+----+------------+---------------------+ --> last row inserted
我尝试使用此代码来显示所有具有“旅行”状态的货物,但是一条货物具有2个历史记录,状态为“旅行”和“已取消”(插入了最后一个记录),仍然向我显示了结果。
$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();
}
}
此代码显示所有记录,状态为“旅行”。我想在他的历史记录中显示带有“旅行”状态的货物,除非它是最后一个记录。
答案 0 :(得分:0)
您可以使用Laravel Query Builder
$latestHistoric= DB::table('freight_historics')
->latest()
->first();