删除该类别后,我可以将图像的category_id更改为null吗?

时间:2018-12-23 04:24:05

标签: php laravel eloquent

我有2个表-imagescategoriesimages表有一个名为category_id的列,该列获取此图像所分配到的类别的ID。我尝试将category_id设置为外键,但该键在级联时会被删除,但无法正常工作,也许我没有正确执行此操作。

    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')
              ->references('id')
              ->on('users')
              ->onDelete('cascade');
        $table->integer('category_id')->nullable()->default(null)->unsigned();
        $table->foreign('category_id')
              ->references('id')
              ->on('categories')
              ->onDelete('cascade');
        $table->string('image_file_name');
        $table->timestamps();
        $table->engine = 'InnoDB';
    });

我收到的错误是:

SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL   :alter table images添加约束images_category_id_foreign外部   键(category_id)引用删除级联上的categoriesid

解决了迁移问题后,事实证明-> onDelete('cascade')不是我想要的。我只想在删除图像时将category_id设置为NULL,而不是同时删除图像。

2 个答案:

答案 0 :(得分:1)

迁移文件的顺序会影响外键,因此,有两种方法可以解决此类问题:

  • 以特定顺序创建表,因此必须在相关表之后创建外键。

  • OR 为外键创建新迁移,但是请确保在两个表之后都创建了该迁移文件。


对于第二个问题: 调用onDelete('cascade');将删除与您要删除的类别相关的所有图像。

现在,如果要将外键 category_id 设置为null,只需将其替换为->onDelete('set null')

希望这会有所帮助。

答案 1 :(得分:0)

此迁移没有任何错误,我认为您应该检查类别表是否存在以及类别表中的id列是否为无符号整数(increment())。 我在系统上测试了此迁移,并且运行良好。

{   "compileOnSave": false,   "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]   },   "exclude": [
    "bower_components/**",
    "node_modules/**",
    "typings/main.d.ts",
    "typings/main/**",
    "typings/index.d.ts"   ] }