6
votes

When i run migrations to create foreign key constraints I get the following error in my command prompt. I need help to overcome it as i searched a lot on internet and tried variety of things but unfortunately none has worked

In Connection.php line 647:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error i n 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 ( SQL: alter table category_posts add constraint category_posts_post_id_fo reign foreign key (post_id) references posts () on delete cascade)

In Connection.php line 445:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error i n 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

My migration code for foreign key constraint 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');
    }
}

Kindly help me out. Thank you

2

2 Answers

13
votes

You just misspelt references

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

use references() instead of referances()

9
votes

You having spelling mistake in migration

Exist code

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

New code

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