Laravel belongsTo - 指定字段
Laravel belongsTo - Specifying fields
我正在处理 belongsTo 关系,但需要知道如何指定要关联的字段。
我有一份报告和一辆车 table。
汽车 table 的 ID 字段为 UI。当对汽车进行报告时,我希望将该车从列表中删除,以便我使用示波器。
在我的报告 table 中,我将汽车 ID 存储为 'vehicle_id'。
我有属于:
public function deliveryProfitReports()
{
return $this->belongsTo('DeliveryProfitReport', 'vehicle_id');
}
它正在返回错误,因为它正在寻找汽车 table 中的 vehicle_id 字段。
如何更改此功能,使其指定汽车 ID 为 vehicle_id。
编辑:修复错误:
public function deliveryProfitReports()
{
return $this->belongsTo('DeliveryProfitReport', 'id', 'vehicle_id');
}
但是这个范围:
public function scopeNoDeliveryReports($query) {
return $query->doesntHave('deliveryProfitReports');
}
$cars = Car::orderBy('RegistrationNumber')
->noDeliveryReports()
->get();
没有按预期工作并删除行...
下一步是什么?
如果外键在 other table 你实际上想使用 hasOne
:
return $this->hasOne('DeliveryProfitReport', 'vehicle_id');
(此外,由于数据类型错误,OP 还存在数据库问题)
我正在处理 belongsTo 关系,但需要知道如何指定要关联的字段。
我有一份报告和一辆车 table。
汽车 table 的 ID 字段为 UI。当对汽车进行报告时,我希望将该车从列表中删除,以便我使用示波器。
在我的报告 table 中,我将汽车 ID 存储为 'vehicle_id'。
我有属于:
public function deliveryProfitReports()
{
return $this->belongsTo('DeliveryProfitReport', 'vehicle_id');
}
它正在返回错误,因为它正在寻找汽车 table 中的 vehicle_id 字段。
如何更改此功能,使其指定汽车 ID 为 vehicle_id。
编辑:修复错误:
public function deliveryProfitReports()
{
return $this->belongsTo('DeliveryProfitReport', 'id', 'vehicle_id');
}
但是这个范围:
public function scopeNoDeliveryReports($query) {
return $query->doesntHave('deliveryProfitReports');
}
$cars = Car::orderBy('RegistrationNumber')
->noDeliveryReports()
->get();
没有按预期工作并删除行...
下一步是什么?
如果外键在 other table 你实际上想使用 hasOne
:
return $this->hasOne('DeliveryProfitReport', 'vehicle_id');
(此外,由于数据类型错误,OP 还存在数据库问题)