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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With