so I use my project locally and run this code php artisan migrate
everything works perfectly fine and my tables will be created
but when I move to my vps and do the same thing I get this error
[Illuminate\\Database\\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table
mediables
add constraintmediables_media_id_foreign
forei gn key (media_id
) referencesmedia
(id
) on delete cascade)
I followed some solution from this site but they didn't work
my migration file :
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('old_name')->nullable();
$table->text('desc')->nullable();
$table->string('category')->nullable();
$table->string('type');
$table->string('format');
$table->string('href');
$table->string('thumbnail')->nullable();
$table->timestamps();
});
Schema::create('mediables', function (Blueprint $table) {
$table->integer('media_id')->nullable();
$table->integer('mediable_id');
$table->string('mediable_type');
$table->primary(['media_id','mediable_id','mediable_type']);
$table->timestamps();
});
Schema::table('mediables', function (Blueprint $table) {
$table->foreign('media_id')
->references('id')->on('media')
->onDelete('cascade');
});
note that there is a polymorphic relation between media and other models in my project
the only difference between my local machine and my vps is that I have apache locally and nginx on vps if it's related
media
table should have id
column, because media_id
references to it.
Also, if id
is increment()
, you should use unsigned()
foreign key:
$table->integer('media_id')->unsigned()->nullable();
if you're using new WAMP take care of it's mysql as it's by default will accept any relation even between non-existing columns like
$table->foreign('media_id')
->references('id')->on('media')
->onDelete('cascade');
the id
isn't existing in media
table.
Also $table->primary(['media_id','mediable_id','mediable_type']);
won't run as you've already set a primary id
as $table->increments('id');
will set id
as a primary.
You have to set table engine to InnoDB
by default or set it explicitly with
$table->engine = 'InnoDB';
Only the InnoDB
engine handles foreign key constraints.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.