Laravel / MySQL - 外键约束错误& belongsToMany有连接

时间:2016-02-29 14:44:18

标签: php mysql eloquent foreign-keys laravel-5.1

框架:Laravel 5.1.28。

MySQL:5.6.16

迁移我收到的firemen表或victims表时:General error: 1215 Cannot add foreign key constraint。即使只创建一个列名为fireman_id的表,也会生成相同的表,即使它不是外键。

users
    id (char36, uuid)
    first_name (varchar, 60)
    last_name (varchar, 60)

firemen
    fireman_id (char36, uuid) - primary foreign which references(id) on (users)

victims
    victim_id (char36, uuid) - primary foreign which references(id) on (users)

fireman_victim
    fireman_id (char36, uuid) - foreign which references(fireman_id) on (firemen)
    victim_id (char36, uuid) - foreign which references(victim_id) on (victims)
  1. 显而易见的是,为什么会出现错误?
  2. 如何在执行以下操作时加入users表以获取名称数据?
  3. 这是我的模特:

    public function victims()
    {
        return $this->belongsToMany('App\Victim', 'fireman_victim', 'fireman_id', 'victim_id');
    }
    

    在我的控制器中:

    $fireman = Fireman::first();
    
    $fireman->victims();
    

    我能做到这一点但有更简单的方法(Eager Loading?belongsToManyThrough)?

    $fireman->victims()->join('users', 'users.id', '=', 'victims.victim_id')->select('first_name', 'last_name);
    

0 个答案:

没有答案