框架: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)
这是我的模特:
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);