SQLSTATE [HY000]:常规错误:1215无法添加外键约束Laravel 5.4

时间:2018-11-14 09:56:58

标签: php laravel migration laravel-5.4

我有一个问题,用Laravel的迁移无法解决。

这是我的用户迁移,数据名称为:2014_12_10_000000_create_users_table.php

public class Excel_Import extends BaseAction {

    public Excel_Import(WebDriver driver) { super(driver); }

public void importExcel(Map<String, Object[]> data) {
    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Data");

    //Iterate over data and write to sheet
    Set<String> keyset = data.keySet();

    int rownum = 0;
    for (String key : keyset)
    {
        //create a row of excel sheet
        Row row = sheet.createRow(rownum++);

        //get object array of particular key
        Object[] objArr = data.get(key);

        int cellnum = 0;

        for (Object obj : objArr)
        {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String)
            {
                cell.setCellValue((String) obj);
            }
            else if (obj instanceof Integer)
            {
                cell.setCellValue((Integer) obj);
            }
        }
    }
    try
    {
        //Write the workbook in file system
        FileOutputStream out = new FileOutputStream(new 
File("D:\\Projects\\Cucumber\\src\\main\\resources\\ImportedResults.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("howtodoinjava_demo.xlsx written successfully on 
disk.");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

这是公司表迁移,文件名为2018_06_01_080858_create_company_table.php

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

            $table->unsignedInteger('user_parent_id')->nullable();
            $table->unsignedInteger('company_id')->nullable();

            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();

        });

这是设置外键的迁移,文件名是:2018_11_13_111338_alter_foreign_keys.php

Schema::create('company', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
             ....
            $table->timestamps();
        });

当我尝试运行php artisan:migrate时,我总是会遇到此错误:

Schema::table('users', function($table) {
          $table->foreign('user_parent_id')->references('id')->on('users');
          $table->foreign('company_id')->references('id')->on('company');
      });

最后,进行迁移,命名为2018_11_13_111338_alter_foreign_keys.php,我为数据库中的所有其他表依次添加了所有其他外键。

所有建议都值得欢迎,谢谢。

这是alterForeignTable类的代码:

    In Connection.php line 647:                                                                               
      SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `company` (`id`))                 

In PDOStatement.php line 144:                                                                          
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint      
In PDOStatement.php line 142:                                                                          
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

2 个答案:

答案 0 :(得分:1)

您有两个模型,并添加了两个外部ID。这是许多工作。您只需要在本文中添加带有company_id和user_id的数据透视表

https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

答案 1 :(得分:1)

首先,您必须将user_id字段设为索引:

$table->index('user_id');

之后,您可以创建一个外键,并对其进行级联操作:

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

如果要使用新迁移进行此操作,则必须首先删除索引和外键,然后从头开始做所有事情。

在down()函数上,您必须执行此操作,然后在up()函数上,执行我上面写的内容:

$table->dropForeign('user_parent_id');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
  

尝试一下,希望它能起作用。