MoeSaid
86
10
Laravel

Cannot add foreign key constraint

Posted 3 months ago by MoeSaid

Hi guys , first time i face this error all work find on my local env but when i import the Db to my server i get it .

here's the schema of my table

public function up()
    {
        Schema::create(config('follow.followable_table', 'followables'), function (Blueprint $table) {
            $userForeignKey = config('follow.users_table_foreign_key', 'user_id');
            $table->unsignedInteger($userForeignKey);
            $table->unsignedInteger('followable_id');
            $table->string('followable_type')->index();
            $table->string('relation')->default('follow')->comment('follow/like/subscribe/favorite/upvote/downvote');
            $table->softDeletes();
            $table->timestamps();

            $table->foreign($userForeignKey)
                ->references(config('follow.users_table_primary_key', 'id'))
                ->on(config('follow.users_table_name', 'users'))
                ->onUpdate('cascade')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::table(config('follow.followable_table', 'followables'), function ($table) {
            $table->dropForeign(config('follow.followable_table', 'followables').'_user_id_foreign');
        });

        Schema::drop(config('follow.followable_table', 'followables'));
    }

here is the error

http://take.ms/1jIIB

Error
SQL query:

CREATE TABLE  `followables` (

 `user_id` INT( 10 ) UNSIGNED NOT NULL ,
 `followable_id` INT( 10 ) UNSIGNED NOT NULL ,
 `followable_type` VARCHAR( 191 ) COLLATE utf8mb4_unicode_ci NOT NULL ,
 `relation` VARCHAR( 191 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT  'follow' COMMENT  'follow/like/subscribe/favorite/upvote/downvote',
 `deleted_at` TIMESTAMP NULL DEFAULT NULL ,
 `created_at` TIMESTAMP NULL DEFAULT NULL ,
 `updated_at` TIMESTAMP NULL DEFAULT NULL ,
KEY  `followables_user_id_foreign` (  `user_id` ) ,
KEY  `followables_followable_type_index` (  `followable_type` ) ,
CONSTRAINT  `followables_user_id_foreign` FOREIGN KEY (  `user_id` ) REFERENCES  `users` (  `id` ) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

MySQL said: Documentation

#1215 - Cannot add foreign key constraint 

any idea what went wrong ?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.