2
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.

4
  • 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 Commented Feb 9, 2014 at 17:55
  • 1
    Maybe you can post this as an answer for future reference. Commented Feb 9, 2014 at 18:15
  • I don't have enough reputation. Please do it for me. Tnx Commented Feb 10, 2014 at 6:02
  • You can answer it, you don't need rep for this to answer and if you answer it then someone may up vote it or maybe I, so your rep will increase. You can even accept your own answer. Commented Feb 10, 2014 at 18:25

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.