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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22884898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:18:59  来源:igfitidea点击:

Insert Laravel model with multiple foreign keys

phplaraveleloquent

提问by troytc

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 violationerror 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?

这会Integrity constraint violation从 SQL 中抛出错误,因为它只更新一个外键。以相反的方式(保存到视频)会产生相同的结果。如何一次将它添加到两个模型,更新两个外键?

回答by gpopoteur

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

你现在遇到的问题是,你懒加载commentsAuth::user

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

我相信你可以做的一件事是使用associateEloquent Models 中的方法,请试试这个,看看它是否适合你的特定需求。

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