mercredi 10 mai 2017

Laravel Many to Many Relationship to join two models

I struggle to get this right with Laravel 5. However, in Rails, I can easily do this:

A User can be a part many Teams. We know that tables User and Team could not have a relation id so I wont post those schema here but instead I have a TeamUser table:

Schema::create('team_users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->integer('team_id');
    $table->timestamps();
});

TeamUser.php:

public function user()
{
  return $this->belongsTo(User::class);
}

public function team()
{
  return $this->belongsTo(Team::class);
}

Team.php

public function users()
{
  return $this->hasManyThrough(User::class, TeamUser::class);
}

User.php

public function teams()
{
  return $this->hasManyThrough(Team::class, TeamUser::class);
}

It seems as if laravel's doc and other tutorials I have seen are different. Im new to Laravel, again, and I need this setup.

Tinker:

$tu = App\TeamUser::create([ 'user_id' => 1, 'team_id' => 1 ]);

Illuminate\Database\Eloquent\MassAssignmentException with message 'user_id'

Expected:

$tu->users // is_array($tu) to be true

Could someone please explain what is wrong here? Thanks much.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire