Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Laravel model with multiple foreign keys

Here's my situation: a User can Comment on a Video. 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 throws a Integrity constraint violation error from SQL, because it only updates one foreign key. Doing it the opposite way (saving to the video) produces the same result. How do I add it to both models at once, updating both foreign keys?

like image 753
troytc Avatar asked Apr 05 '14 18:04

troytc


1 Answers

The problem you're having right now is that you're lazy loading the comments of the Auth::user.

One thing you can do I believe, is to use the associate method in the Eloquent Models, please 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();
like image 185
gpopoteur Avatar answered Oct 14 '22 04:10

gpopoteur