unable to create foreign key in laravel.

Discussion for various published PHP frameworks, including Zend Framework, CodeIgniter, Kohana, CakePHP, Yii, Symfony, and others.

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

unable to create foreign key in laravel.

Post by gautamz07 »

I have the following migration for my tags table:

Code: Select all

Schema::create('tags', function (Blueprint $table) {
         $table->increments('id');
            // $table->mediumText('tag');
         $table->char('tag' , 15);
 });
Then i have the following migration for my admin table:

Code: Select all

public function up()
    {
        Schema::create('admin', function (Blueprint $table) {
            $table->increments('id');
            $table->mediumText('title');
            $table->text('blog_content');
            $table->char('tag' , 15);
            $table->string('filePath');
            $table->string('slug');
            $table->timestamps();
        });

        Schema::table('admin', function (Blueprint $table) {
            $table->foreign('tag')->references('tag')->on('tags');
        });
    }


Now when i check the laravel docs the examples of foreign keys are all for primary keys:
see here https://laravel.com/docs/5.0/schema#foreign-keys

Does a foreign key always need to be a primary key ??

The tables i have created are of type "InnoDB" .. i get the following error:

http://i.imgur.com/aRaln7s.png

Thank you.
Gautam.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: unable to create foreign key in laravel.

Post by Celauran »

The field you're referencing needs to be indexed. Also, why wouldn't you reference the primary key? What's the thinking with having two CHAR(15) fields referencing each other?
Post Reply