Schema::create('position', function (Blueprint $table) {
$table->increments('post_id');
$table->String('post_name');
$table->timestamps();
});
Schema::create('candidate', function (Blueprint $table) {
$table->increments('id');
$table->String('name');
$table->String('branch');
$table->unsignedInteger('post_id');
// $table->foreign('post_id_no')->references('post_id')->on('position')->onDelete('cascade');
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
$table->integer('count')->default(0);
$table->timestamps();
});
I have two tables, position
and candidate
. When I migrate I get error for foreign key. can anyone say whats error in code?
This is error I get when I migrate:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table
voting
.#sql-16b7_2b
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablecandidate
add constraintcandidate_post_id_foreign
foreign key (post_id
) referencesposition
(post_id
) on delete cascade)
catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `voting`.`#sql-16b7_2b` (errno: 150 "Foreign key constraint is incorrectly formed")")
答案 0 :(得分:0)
很可能外键列和引用列的不匹配可能不是相同的类型或长度。代替
$table->unsignedInteger('post_id');
在您的candidate
表中,尝试:
$table->integer('post_id')->unsigned()->index();
此外,有时将原始(position
)id保留为'id'有时会很有帮助,而且更加清晰(也许是mysql)。您可以在candidate
表中将其称为post_id,并在position
上引用“ id”。有点容易理解。
答案 1 :(得分:0)
您需要将默认引擎指定为
$table->engine = 'InnoDB';
并确保已创建表position
所引用的candidate
表。也请在帖子中添加您的投票表架构。
答案 2 :(得分:0)
您可以尝试一下。
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
这对我有用。谢谢。
答案 3 :(得分:0)
public function up() { Schema::create('companies', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('address'); $table->string('tel1'); $table->string('tel2'); $table->integer('owner'); $table->unsignedBigInteger('access_id'); $table->string('depot_number')->default(2); $table->timestamps(); $table->foreign('access_id')->references('id')->on('accesses') ->onDelete('cascade'); }); }
public function up() { Schema::create('accesses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->string('description'); $table->timestamps(); }); }
在您的数据库/迁移文件夹中,按名称排序。然后确保 create_accesses_table 在 create_companies_table 之前: enter image description here