【发布时间】:2020-04-30 10:55:55
【问题描述】:
我正在开发一个项目来跟踪货物的交付。 我的想法是一次送货可以去不同的地方,所有这些地方都通过单程连接。
这是我的 Eloquent 架构:
class Delivery extends Model
{
public function places()
{
return $this->hasMany(Place::CLASS, 'delivery_id');
}
public function trips()
{
// what should I do here?
}
}
class Place extends Model
{
public function delivery()
{
return $this->belongsTo(Delivery::CLASS, 'delivery_id');
}
}
class Trip extends Model
{
public function departurePlace()
{
return $this->belongsTo(Place::CLASS, 'departure_place_id');
}
public function arrivalPlace()
{
return $this->belongsTo(Place::CLASS, 'arrival_place_id');
}
}
基本上,我要做的是获取与一次交付相关的所有行程。或者,换一种说法,连接一次送货必须经过的所有地方的所有行程。 这是实现我想要的结果的 SQL 查询:
select distinct trip.*
from delivery
join place on (place.delivery_id = delivery.id)
join trip on (place.id = trip.arrival_place_id or place.id = trip.departure_place_id)
我想在我的 Delivery 模型上有一个 trips() 方法,它返回该结果。
但是,我对如何使用 Eloquent 实现这一点感到非常困惑。
【问题讨论】:
-
从我上面看到的查询来看,送货和旅行之间似乎没有直接联系。如果我正确理解了查询,那将返回曾经在交货地点进行的所有旅行。
-
是的,完全正确。送货和旅行之间没有联系。需要首先通过场所连接,如 SQL 查询所示。抱歉,我刚刚注意到我的问题中有一个错误。
-
您的意思是获取所有通过地点的送货行程吗?
-
@Saengdaet 是的,我就是这个意思。