使用Eloquent Laravel定义表与链接表主键的关系

时间:2017-03-23 10:39:54

标签: mysql database laravel eloquent

您好我正试图弄清楚如何在雄辩中定义这种关系: Image Of Schema

我使用的很多人将制造商和设备类型链接在一起,例如:

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]:未找到列:1054未知列' manufacturers.equipment_types_manufacturers_id'在' where子句' (SQL:select * from equipment_models where where(select {from manufacturers where equipment_modelsequipment_types_manufacturers_id = manufacturersequipment_types_manufacturers_id和{{1 }} = 1)并存在(从manufacturer_id中选择* equipment_typesequipment_models = equipment_types_manufacturers_idequipment_typesequipment_types_manufacturers_id = 1))

我觉得这可以通过为链接表创建模型来实现,但我不确定这是否正确?

1 个答案:

答案 0 :(得分:0)

您正在尝试通过其他模型/表格获取模型。您需要使用hasManyThrough()。在您的制造商型号中,尝试

public function equipments() {
    return $this->hasManyThrough(
        'EquipmentModel', 'EquipmentTypesManufacturer',
        'manufacturer_id', 'etml_id', 'id'
    );
}

在此处阅读更多内容:https://laravel.com/docs/5.4/eloquent-relationships#has-many-through