简体   繁体   中英

Unable To Create Foreign key In Laravel With Mysql

I have a project and i have call these 2 commands at the first in my command prompt:

php artisan make:model Music -m
php artisan make:model Artist -m

Then i create a foreign key in music migration file like this :

public function up()
{
    Schema::create('musics', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('artist_id')->unsigned();
        $table->timestamps();
        $table->foreign('artist_id')->references('id')->on('artists');
    });
}

Now when i run migrate command like :

php artisan migrate

But i have a this error :

       Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `musics` add constraint `musics_artist_id_foreign` foreign key (`artist_id`) references `artists` (`id`) on delete cascade)

  at D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

Note : i will test a few ways like set index to both of fields,...

Ordering issue. You have to create the artists table first. musics.artist_id can't reference a key that doesn't exist yet:

php artisan make:model Artist -m
php artisan make:model Music -m

Ensure the artists table migration runs before the musics migration. You can't make a foreign key on nothing!

Also, ensure the column on both tables are identical, in other words both the foreign key column and original primary key must both be unsigned integers in this case.

Finally, it's better practice to include the onUpdate() and onDelete() methods when defining your foreign key contraint, this makes it easier to debug/read later.

In your case you would do:

$table->foreign('artist_id')->references('id')->on('artists')->onUpdate('cascade')->onDelete('cascade');

You should have a artists table first then foreign a artist id. First try to create a artist model.

I dont't have any mistake in create migrations file.

My mistake is in create function for realation in Artist model :

In my Artist.php i used :

public function music(){ ... }

Now i forget to set like this :

public function musics(){ ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM