Skip to content
Advertisement

laravel, migration reference table string format on delete cascade

How can I make relation between two table using string format? I’m getting the error

SQLSTATE[HY000]: General error: 1005 Can’t create table ....ordercustomizes (errno: 150 “Foreign key constraint is incorrectly formed”) (SQL: alter table ordercustomizes add constraint ordercustomizes_userorder_id_foreign foreign key (userorder_id) references userorders (order_number) on delete cascade)

    Schema::create('ordercustomizes', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('userorder_id');
        $table->integer('product_id')->unsigned();
        $table->integer('customizetitle_id')->unsigned();
        $table->integer('customizeproduct_id')->unsigned();
        $table->timestamps();

            $table->foreign('userorder_id')
            ->references('order_number')
            ->on('userorders')
            ->onDelete('cascade');

main table:

   Schema::create('userorders', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('product_id')->unsigned();
        $table->integer('storeinfo_id')->unsigned();
        $table->integer('user_id')->unsigned();
         $table->string('order_number');          

Advertisement

Answer

You need to create an index for the order_number field (in userorders table) first.

You can do it at table creation using: $table->string('order_number')->index();
Or you can alter the existing table and just create a new index using: $table->index('order_number');

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement