问题
I'm trying to add a foregin key which references an integer primary key in the reference table. I'm facing two issues with the way laravel is trying to create the table the first is that if I try to explicitly enter the foreign key columns integer length of 11 to match the reference column it thinks that I want this column as a primary key? And I get the error:
"Incorrect table definition; there can only be one auto column and it must be defined as a key"
Even if I explicitly state the primary key as the 'id' column I get this error. Here is the code I am using to produce this error:
public function up()
{
Schema::create('ip_bans', function(Blueprint $table)
{
$table->increments('id');
$table->string('ip_address', 255);
$table->integer('ban_id', 11);
$table->primary('id');
$table->foreign('ban_id')->references('id')->on('user_bans')->onDelete('set null');
});
}
Here is the schema for the reference table:
public function up()
{
Schema::create('user_bans', function(Blueprint $table)
{
$table->increments('id');
$table->string('reason');
$table->string('banned_user', 16);
$table->timestamps();
$table->timestamp('ban_end');
$table->foreign('banned_user')->references('username')->on('users')->onDelete('cascade');
});
}
If I remove the explicit integer length of 11 from the foreign key column I am unable to create the foreign key because the columns don't match since the length of the column is 11 and the reference column in 'user_bans' table is 10. Is there anything I am doing wrong here or a way around this error?
回答1:
Have you tried this?
$table->integer('ban_id', 11)->unsigned;
Laravel - Foreign Keys (note the pink box under this section)
来源:https://stackoverflow.com/questions/27976287/laravel-migration-wont-add-foreign-key-with-integer-type-mysql