首页 > 解决方案 > "laravel Migration Foreign key constraint is incorrectly formed"

问题描述

I have a problem In Laravel and I do not know where the problem is. someone can help me . And thank you in advance. I have two tables (clients, and reparations) I want to make a foreign key with the string field ('cin_client'), when I create the table reparations it does not work anymore /* ************* table clients **************>

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClientsTable extends Migration
{
   public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->Increments('id_client');
            $table->string('nom_client');
            $table->string('prenom_client'); 
            $table->string('adresse_client'); 
            $table->string('tel_client'); 
            $table->string('cin_client',30); 

            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}

/************* Table reparations *************/

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateReparationsTable extends Migration
{
    public function up()
    {
        Schema::create('reparations', function (Blueprint $table) {
            $table->Increments('id_reparation');
            $table->string('type_reparation')->nullable();
            $table->string('date_reparation')->nullable();
            $table->integer('prix_reparation')->nullable();
            $table->string('genre_marque_type')->nullable();

            $table->boolean('etat_reparation')->nullable(); 

/*$table->foreign('client_cin')->references('cin_client')->on('clients');*/
            $table->timestamps();
$table->string('client_cin',30);
        });

        Schema::table('reparations', function (Blueprint $table){
            $table->foreign('client_cin')->references('cin_client')->on('clients');

        });
    }
    public function down()
    {
        Schema::dropIfExists('reparations');
    }
}

标签: phpdatabaselaravelmigration

解决方案


因此,该数据库错误几乎总是意味着您为保存第一个表中的外键引用而定义的列,而您在第二个表中定义的列的格式或长度不匹配。查看迁移(不确定您使用的是什么 DBS)我认为您需要->unsigned()从 reparations.client_cin 的列定义中删除。


推荐阅读