我有一个
Timeline
模型,带有 start
和 end
时间戳(以及其他详细信息)。
我想创建一个关系,以便我可以跳转到下一个/上一个活动。
它们不是按顺序添加的,所以我不能依赖
id
。
例如
Timeline::query()
->where('type', $timelineType)
->with('previousTimeline')
->limit(5)
->orderByDesc('start')
->get()
希望将
hasOne()->ofMany()
与自定义闭合一起使用,例如:
// app/Models/Timeline
public function previousTimeline(): HasOne
{
return $this->hasOne(self::class, 'id', 'id')
->ofMany(['start' => 'max'],
// fn($q) => $q->where('start', '<', '2013-09-04 13:27:47') // this works
fn($q) => $q->where('start', '<', $parentStart) // how to refer to the "parent" timeline?
);
}
但是如何在
ofMany()
闭包中引用“父”时间线?
或者:推荐的方法是什么?
您可以在
Timeline
模型中定义两个函数来确定查询范围
public function previousTimeline($query, $startTime) {
return $query->where('start', '<', $startTime)
->orderByDesc('start')
->limit(1);
}
public function nextTimeline($query, $startTime) {
return $query->where('start', '>', $startTime)
->orderBy('start')
->limit(1);
}
然后您可以这样调用此查询:
$previousTimeline = Timeline::query()
->previousTimeline($timeline->start)
->first();
$nextTimeline = Timeline::query()
->nextTimeline($timeline->start)
->first();
$nextTimeLine
或 $previousTimeLine
可以用作父级