Ahmet Çelikezer
Ahmet Çelikezer

Reputation: 37

Laravel Migration Foreignkey Error

Laravel 5.6 running on: PHP 7.2, MariaDB 10.3

When I want to set foreign key for my table, I just keep taking that error.

On other tables, all id variables defined by Laravel itself and auto increments unsigned

So, my Migration is like this:

public function up()
{

    Schema::create('user_roles', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('role_id');
        $table->unsignedInteger('user_id');

        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

The error is like this:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') on delete cascade' at lin e 1 (SQL: alter table user_roles add constraint user_roles_role_id_foreign foreign key (role_id) references roles () on delete cascade)

Errors thrown by Laravel:

1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') on delete cascade' at line 1") C:\xampp\htdocs\order-project\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452

2 PDO::prepare("alter table user_roles add constraint user_roles_role_id_foreign foreign key (role_id) references roles () on delete cascade") C:\xampp\htdocs\order-project\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452

Upvotes: 1

Views: 1202

Answers (3)

Ahmet Çelikezer
Ahmet Çelikezer

Reputation: 37

I solved the problem. It fails because of Laravel trying to migrate user_roles table before the roles table. I just migrate roles table before the user_roles table and it's worked! Before the solution rules table is not throwing an error but it's not completely created.

Upvotes: 0

Mustafa Salim
Mustafa Salim

Reputation: 21

I think you have similiar problem with this post Laravel foreign key onDelete('cascade') not working

Hope this can help

Upvotes: 0

Alexander Villalobos
Alexander Villalobos

Reputation: 461

try this

$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Upvotes: 0

Related Questions