php – 使用多个外键插入Laravel模型

这是我的情况:用户可以评论视频.评论同时属于视频和用户.我的模型看起来像这样:
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');
    }
}

我正在尝试插入评论:

$comment = new Comment;
$comment->content = 'content';
Auth::user()->comments()->save($comment);

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

你现在遇到的问题是你懒得加载Auth :: user的注释.

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


laravel的dd函数不生效怎么办
看不懂laravel文档咋办
安装laravel框架出现command怎么办
Laravel开发API怎么使用事务
laravel怎么构建复杂查询条件
laravel如何实现防止被下载
为什么laravel比yii火
一些常见的Laravel定时任务不运行的问题
laravel用路由有什么好处
composer无法安装laravel怎么办
laravel现在还用吗
laravel怎么替换主键id
laravel的appurl有什么用
如何修改Laravel的报错输出形式
laravel怎么避免foreach查表
laravel怎样操作数据库
laravel怎么截取字符串
laravel 是国内的吗
laravel怎么设置请求头
浅析Laravel社区Redis组件报错的问题和解决方法