php - Laravel 5 使用外键插入行

标签 php mysql laravel-5

我有两个表 Users 和 Posts。 这是我的用户表迁移文件:

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->string('password_temp',60);
        $table->integer('active');
        $table->string('code',60);
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}

这是我的帖子表迁移文件

public function up()
{
    Schema::create('posts', function(Blueprint $table){

        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->integer('user_id')->unsigned();
        $table->string('slug');
        $table->timestamps();


    });

    Schema::table('posts',function(Blueprint $table){

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

    });
}

AdminPostsController 扩展 Controller { 公共(public)函数存储(请求 $request) {

    $validator = Validator::make($request->all(),Post::$rules);


    if($validator->passes()){



        $post = new Post();

        $post->title = $request->get('title');
        $post->body = $request->get('body');
        $post->user_id = $request->get('id');
        $post->slug = Slug::generateSlug($request->get('title'));

        $post->save();

        return Redirect::route('admin.posts.index');
    }
    else{
            return Redirect::route('admin.posts.create')->withErrors($validator)->withInput();
    }

}

每次我插入一个新帖子,我总是看到以下错误

"Connection.php 第 614 行中的 QueryException: SQLSTATE [23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败('blog'。'posts',CONSTRAINT 'posts_user_id_foreign' FOREIGN KEY('user_id')REFERENCES 'users'('id ') 在更新级联上删除级联)"

我想知道我做错了什么。

最佳答案

此代码创建一个约束,以便您的帖子必须由有效的用户 ID 引用。 user_id 字段必须包含用户表 id 字段上的现有键。

    $table->foreign('user_id')
        ->references('id')
        ->on('users')

在保存新帖子之前尝试关联用户。

$post        = new Post();
$post->title = $request->get('title');
$post->body  = $request->get('body');

$post->user()->associate($user);
$post->save();

假设您在 $user var 上加载了一个有效的用户模型,并且您已经在模型上设置了用户和帖子之间的关系。

关于php - Laravel 5 使用外键插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858067/

相关文章:

php - Laravel 5 中的图像数组验证

php - MySQL:如何根据结果是否也存在于其他表中来对结果进行排序?

mysql - 安装 MySQL-Server 时如何防止安装 MariaDB?

php表单通过基本认证restful api提交

Mysql 和 case 语句不起作用

mysql - 获取具有分组 SQL 结果的最大总和值的记录

javascript - 在 VueJS 中从父组件中引用子组件的索引

mysql - 当我尝试显示一列的计数值时,它会计算编号。存储在同一个表的同一行的单个单元格中的数组的数量

javascript - SyntaxError : JSON. 解析:尝试插入 mysql 时,JSON 数据的第 1 行第 1 列出现意外字符

php - 我可以阻止 vimrc 中的设置被插件覆盖吗?