2015-11-10 13 views
8

मैं एक laravel डेटाबेस प्रवास लिखने की कोशिश कर रहा हूँ, लेकिन मैं एक विदेशी कुंजी के बारे में निम्न त्रुटि हो रही है:Laravel प्रवास को नहीं जोड़ सकते विदेशी कुंजी

[Illuminate\Database\QueryException]                                                      
    SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`)) 



    [PDOException]                       
    SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table 

categories और subcategories टेबल बनाया मिलता है लेकिन विदेशी कुंजी नहीं है। यहां मेरा माइग्रेशन है:

<?php 

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

class CreateCategoryTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('categories', function ($table) { 
      $table->increments('id')->unsigned(); 
      $table->string('name')->unique(); 
     }); 

     Schema::create('subcategories', function ($table) { 
      $table->increments('id')->unsigned(); 
      $table->foreign('category_id')->references('id')->on('categories'); 
      $table->string('name')->unique(); 
     }); 
    } 

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

कोई विचार? धन्यवाद!

+0

आपको ऑटो वृद्धिशील फ़ील्ड की आवश्यकता नहीं है क्योंकि केवल विदेशी कुंजी संदर्भ को हस्ताक्षरित किया गया है। –

उत्तर

18

आप एक विदेशी कुंजी बनाने से पहले स्तंभ बनाने चाहिए:

$table->integer('category_id')->unsigned(); 
$table->foreign('category_id')->references('id')->on('categories'); 

प्रलेखन: http://laravel.com/docs/5.1/migrations#foreign-key-constraints

+0

ओह! मूर्खतापूर्ण गलती। धन्यवाद! –

+0

@RoemerBakker अगर आप मेरे उत्तर से खुश हैं तो आप इसे स्वीकार कर सकते हैं :) –

+0

ऐसा करने में खुशी है! कल जवाब देने के बाद 5 मिनट इंतजार करना पड़ा और इसके बाद इसे स्वीकार करना भूल गया। आपका दिन शुभ हो! ;) –

0

मैं तरीकों मैं बुलाया ->get() जोड़ने के लिए भूल गया था।

संबंधित मुद्दे