php - laravel删除父行数据出错

标签 php mysql database sql-delete laravel-5.5

我想删除广告系列,但不删除广告系列,并出现以下错误。

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (demopurpose_fundraising.campaign_product, CONSTRAINT campaign_product_campaign_id_foreign FOREIGN KEY (campaign_id) REFERENCES campaign (id)) (SQL: delete from campaign where id = 60)

事件表架构:

Schema::create('campaign', function (Blueprint $table) {
            $table->engine='InnoDB';
            $table->increments('id');
            $table->integer('users_id')->unsigned();
            $table->foreign('users_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->string('campaign_name');
            $table->float('campaign_goal',8,2);
            $table->string('discription',400);
            $table->string('image');
            $table->string('category');
            $table->date('start_date');
            $table->date('end_date');
            $table->float('total_fund',8,2);
});

campaign_product 表架构:

Schema::create('campaign_product', function (Blueprint $table) {
            $table->engine='InnoDB';

            $table->increments('id');
            $table->integer('campaign_id')->unsigned();
            $table->foreign('campaign_id')->references('id')->on('campaign')->onDelete('cascade')->onUpdate('cascade');

            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('product')->onDelete('cascade')->onUpdate('cascade');
        });

最佳答案

您应该更新迁移以在删除时执行某些操作。请参阅:https://laravel.com/docs/4.2/schema#foreign-keys

例如(来自文档)

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

根据您选择的数据库,可能还有其他选项,例如设置 null。

这里的问题是你设置了一个约束,但你却惊讶地发现自己受到了约束。设置 onDelete 行为,以便数据库为您进行处理。

关于php - laravel删除父行数据出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49377572/

相关文章:

c# - 如何使用参数从 Access 数据库中保存数字?

php - 在一个sql查询中更新多行

php - 如何不在 php 中进行数据库调用来检查用户角色?

mysql - 如何在进程中打印mysql程序中的sql?

mysql - 在关联Rails中的多个记录中选择特定记录

database - 使用 pgAdmin 导出 Postgresql 表数据

php - 如何在 PHP 中创建函数字典?

PHP 将 REQUEST_URI 解析成数组

mysql - 选择查询不起作用时的情况

mysql - 外键存在,我得到 MySQL 错误 : 1452: Cannot add or update a child row: a foreign key constraint fails