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

标签 mysql database laravel eloquent

您好,我正在尝试弄清楚如何以 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 * from manufacturers where equipment_models.equipment_types_manufacturers_id = manufacturers.equipment_types_manufacturers_id and manufacturer_id = 1) and exists (select * from equipment_types where equipment_models.equipment_types_manufacturers_id = equipment_types.equipment_types_manufacturers_id and equipment_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/

相关文章:

mysql - 检查 mysql 中不同类型用户的单个用户表与两个用户表的性能

mysql - 诊断 2013 与 MySQL 的连接丢失

python - 在 Django 中发布表单时无法保存数据

database - jquery ui 自动完成数据库

php - Laravel 8 Eloquent : How to set OR condition to where clause in Laravel

php - 如果用户在另一个表上有数据,则选择用户

mysql - 获取客户 MySQL 的最近两个日期

php - laravel 中 yajra 数据表的问题

php - 从 MySQLi 字段获取类型规范字符

php - PhpMyAdmin 中的请求与 Laravel 查询生成器一起工作,似乎不起作用