简体   繁体   English

插入具有多个外键的Laravel模型

[英]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. 这会从SQL引发Integrity constraint violation错误,因为它只更新一个外键。 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 . 你现在遇到的问题是你懒得加载Auth::usercomments

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. 我可以做的一件事是,在Eloquent模型中使用associate方法,请尝试这一点,看看它是否适合您的特定需求。

// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM