Insert Laravel Model with Multiple Foreign Keys

Here is my situation: The user can comment on the video. The comment belongs to both the video and the user. My models look like this:

class Comment extends Eloquent { public function video() { return $this->belongsTo('Video'); } public function user() { return $this->belongsTo('User'); } } class User extends Eloquent { public function comments() { return $this->hasMany('Comment'); } } class Video extends Eloquent { public function comments() { return $this->hasMany('Comment'); } } 

And I'm trying to insert a comment:

 $comment = new Comment; $comment->content = 'content'; Auth::user()->comments()->save($comment); 

This causes an Integrity constraint violation error from SQL because it updates only one foreign key. Doing this the other way around (saving video) gives the same result. How to add it to both models at once by updating both foreign keys?

+6
source share
1 answer

The problem you are currently facing is that you are lazy loading comments from Auth::user .

One thing you can do, I believe, is to use the associate method in Eloquent Models, try this and see if it works for your specific needs.

 // Get the video of the comment relation $video = Video::find(Input::get('video_id')) ; // Use the associate method to include // the id of the others model $comment = new Comment; $comment->content = 'content'; $comment->user()->associate(Auth::user()); $comment->video()->associate($video); $comment->save(); 
+19
source

All Articles