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

tro*_*ytc 8 php laravel eloquent

这是我的情况:用户可以评论视频.评论属于视频和用户.我的模型看起来像这样:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试插入评论:

$comment = new Comment;
$comment->content = 'content';
Auth::user()->comments()->save($comment);
Run Code Online (Sandbox Code Playgroud)

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

gpo*_*eur 22

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

你可以做的一件事就是使用associateEloquent模型中的方法,请尝试这一点,看看它是否适合您的特定需求.

// 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();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你@gpopoteur你不知道我花了多少时间来弄清楚如何保存一个有多种关系的新模型.如果您希望新模型仅与新模型的一个实例一起使用,则多态性有效,但如果您希望新模型属于许多"所有者",则不会 (2认同)