foreign führt zu einem Fehler

  • Grüß euch,


    folgender Code führt zu folgendem Fehler.


    Code
    Schema::create('notes', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id')->index();
    $table->unsignedInteger('admin_id')->index();
    $table->text('note');
    $table->timestamps();
    $table->foreign('admin_id')->references('id')->on('users');
    });


    Migrating: 2021_02_02_101233_create_notes_table


    Illuminate\Database\QueryException


    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `notes` add constraint `notes_admin_foreign` foreign key (`admin`) references `users` (`id`))


    at C:\MAMP\htdocs\crm\vendor\laravel\framework\src\Illuminate\Database\Connection.php:678

    674▕ // If an exception occurs when attempting to run a query, we'll format the error

    675▕ // message to include the bindings with SQL, which will make this exception a

    676▕ // lot more helpful to the developer instead of just the database's errors.

    677▕ catch (Exception $e) {

    ➜ 678▕ throw new QueryException(

    679▕ $query, $this->prepareBindings($bindings), $e

    680▕ );

    681▕ }

    682▕


    1 C:\MAMP\htdocs\crm\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471

    PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")


    2 C:\MAMP\htdocs\crm\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471

    PDOStatement::execute()


    Warum? Laut Laraveldoku scheint doch alles richtig zu sein

  • Ich hatte zwar auf Antwort hier gehofft, das Forum scheint aber schon Ausgestorben zu sein.


    Ich konnte das Problem nun selber lösen


    Code
    Schema::create('notes', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id')->index();
    $table->unsignedBigInteger('admin_id')->nullable();
    $table->text('note');
    $table->timestamps();
    $table->foreign('admin_id')->references('id')->on('users');
    });