lundi 29 février 2016

Laravel/MySQL - Error on foreign key contraint & belongsToMany with joins

Framework: Laravel 5.1.28.

MySQL: 5.6.16

When migrating the firemen table or the victims table I receive: General error: 1215 Cannot add foreign key constraint. Even just creating a table with the column name fireman_id produces the same table, even if it's not a foreign key.

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. The obvious, why is the error occuring?
  2. How can I join the users table to get the name data when doing the following?

This is my Model:

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

In my Controller:

$fireman = Fireman::first();

$fireman->victims();

I can do this but is there a simpler way(Eager Loading? belongsToManyThrough)?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire