user3260759
user3260759

Reputation: 513

Pivot Table Laravel 4

class Project extends Eloquent {

       public function users()
       {
         return $this->belongsToMany('User','project_user','project_id','user_id')
         ->withPivot('isLeader');
       }
 }

 class User extends Eloquent {
    public function projects()
    {
        return $this->belongsToMany('Project','project_user','project_id','user_id')
        ->withPivot('isLeader');
    }
 }

my pivot table name is project_user with an extra column "isLeader"..

when I try to attach:

 $user= User::findOrFail($user_id);
 $user->projects()->attach($project_id);

It doesn't work.. I got this error

  Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key   
  constraint fails (`db`.`project_user`, CONSTRAINT `project_user_project_id_foreign` 
  FOREIGN KEY (`project_id`)REFERENCES `projects` (`id`) ON UPDATE CASCADE) (SQL: insert 
  into `project_user` () values ())

However, if I use $projects->user()->attach('userid') instead, it works.

But, I need to fetch $user->projects()... but it is not working.

Upvotes: 2

Views: 252

Answers (1)

user3260759
user3260759

Reputation: 513

Problem was setting up the relationship..

     return $this->belongsToMany('Project','project_user','project_id','user_id')
     ->withPivot('isLeader');

should be..

    return $this->belongsToMany('Project','project_user','user_id','project_id')
     ->withPivot('isLeader');

O.O

Upvotes: 2

Related Questions