Bonjour,

Voila je rencontre un petit problème avec mon code merci

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateQuestionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('questions', function (Blueprint $table) {
            $table->increments('id');
            $table->text('queston');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('questions');
    }
}

Ce que j'obtiens

''''
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table answers add constraint answers_question_id_foreign foreign key (question_id) references questions (id) on delete cascade)

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667| // If an exception occurs when attempting to run a query, we'll format the error
668| // message to include the bindings with SQL, which will make this exception a
669| // lot more helpful to the developer instead of just the database's errors.
670| catch (Exception $e) {

671| throw new QueryException(
672| $query, $this->prepareBindings($bindings), $e
673| );
674| }
675|

  +9 vendor frames

10 database/migrations/2020_04_22_160448_create_answers_table.php:24
Illuminate\Support\Facades\Facade::__callStatic()

  +22 vendor frames

33 artisan:37
Illuminate\Foundation\Console\Kernel::handle()

''''

3 réponses


Bonjour, le problème concerne apparemment la migration 2020_04_22_160448_create_answers_table.
J'ai eu pas mal de problème avec les clés étrangères dernièrement mais j'ai pu réglé tout ça grâce au "Foreign key constrained".

https://laravel.com/docs/7.x/migrations#foreign-key-constraints

Salut,

Les types sont sûrement différent, on voit que tu déclares tes PK avec increment (unsigned int) et ta clé érangère un unsignedBigInteger (unsigned big int), si ta PK dans users est déclarée avec un increment, il faut que tu utilises unsignedInteger pour user_id

Merci beacoup pour vos réponses, j'ai retrouvé l'erreur déja. J'ai en fait des erreur au niveau de la nomination des noms des tables d'oû j'ai du fais une autre migration.