您好,我正在尝试弄清楚如何以 Eloquent 方式定义这种关系: Image Of Schema
我使用 belongs to many 将制造商和设备类型链接在一起,例如:
return $this->belongsToMany('App\Models\EquipmentType','equipment_types_manufacturers',
'manufacturer_id', 'equipment_type_id');
但是在尝试定义关系时我找不到如何从 equipment_model FK etml_id -> equipment_types_manufacturers PK 定义链接
return $this->hasMany('App\Models\EquipmentType','equipment_types_manufacturers',
'equipment_types_manufacturers_id', 'equipment_type_id');
sql中哪个失败
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'manufacturers.equipment_types_manufacturers_id' in 'where clause' (SQL: select * from
equipment_models
where exists (select * frommanufacturers
whereequipment_models
.equipment_types_manufacturers_id
=manufacturers
.equipment_types_manufacturers_id
andmanufacturer_id
= 1) and exists (select * fromequipment_types
whereequipment_models
.equipment_types_manufacturers_id
=equipment_types
.equipment_types_manufacturers_id
andequipment_type_id
= 1))
我觉得这可以通过为链接表创建模型来实现,但我不确定这是否正确?
最佳答案
您正在尝试通过另一个模型/表格获取模型。您需要使用 hasManyThrough()
。在您的 Manufacturer 模型中,尝试
public function equipments() {
return $this->hasManyThrough(
'EquipmentModel', 'EquipmentTypesManufacturer',
'manufacturer_id', 'etml_id', 'id'
);
}
在这里阅读更多:https://laravel.com/docs/5.4/eloquent-relationships#has-many-through
关于mysql - 使用 Eloquent Laravel 定义表与链接表主键的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42973662/