Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel migration syntax error or access violation 1064

Tags:

mysql

laravel

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

like image 885
Khurram Avatar asked Jan 19 '18 06:01

Khurram


2 Answers

You just misspelt references

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

use references() instead of referances()

like image 137
M Shafique Avatar answered Oct 15 '22 22:10

M Shafique


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');
like image 43
Dharmesh Rakholia Avatar answered Oct 15 '22 22:10

Dharmesh Rakholia