Laravel migration syntax error or 1064 access violation

When I run migrations to create foreign key constraints, I get the following error on the command line. I need help to overcome this, since I searched a lot on the Internet and tried different things, but, unfortunately, no one worked.

In the line Connection.php 647:

SQLSTATE [42000]: Syntax error or access violation: 1064 You have an error i n your SQL syntax; check the manual that matches your MariaDB server version for the correct syntax to use next to ') when deleting a cascade' in line 1 (SQL: alter table category_postsadd constraint category_posts_post_id_fo reignforeign key ( post_id) links posts() when deleting a cascade)

On line 445 Connection.php:

SQLSTATE [42000]: Syntax error or access violation: 1064 You have an error i n your SQL syntax; check the manual that matches your MariaDB server version for the correct syntax to use next to ') when deleting the cascade' on line 1

My migration code to restrict the foreign key is as follows

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

class CreateCategoryPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category_posts', function (Blueprint $table) {
            $table->integer('category_id')->unsigned()->index();
            $table->integer('post_id')->unsigned()->index();
            $table->foreign('post_id')->referances('id')->on('posts')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

Please help me. Thanks you

+4
source share
2 answers

You have a spelling error in migration

Existing code

$table->foreign('post_id')->referances('id')->on('posts')->onDelete('cascade');

New code

 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
+5
source

You just skip the links

$table->foreign('post_id')->referances('id')->on('posts')->onDelete('cascade');

use references()insteadreferances()

+4
source

Source: https://habr.com/ru/post/1692404/


All Articles