2017-04-24 74 views
0

需要幫助傢伙!我的遷移有什麼問題,它不會創建users表和posts表之間的關係。下面是我所做的:Laravel 5.1中的外鍵 - 無關係

  1. 遷移用戶表
  2. 創造職位表
  3. 遷移職位表的外鍵

用戶遷移

<?php 

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

class CreateUsersTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('users', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('name'); 
      $table->string('email')->unique(); 
      $table->string('password', 60); 
      $table->rememberToken(); 
      $table->timestamps(); 
     }); 
    } 

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



帖子遷移

<?php 

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

class CreatePostsTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('posts', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->string('title', 255); 
      $table->text('content'); 
      $table->timestamps(); 

      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
     }); 
    } 

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



沒有發生與我的數據庫。看看我的數據庫:

enter image description here



相比本:

enter image description here



..我使用Laravel 5.1

+0

任何錯誤?發佈到? –

+0

檢查數據庫的列定義(類型,大小)是否相等。 –

+0

@MayankPandeyz沒有錯誤顯示。 –

回答

2

您需要分兩步添加。 Schema::create()僅用於創建表格。

要添加關係,您需要在Schema::table()內編寫關係。

嘗試以下操作:

CreatePostsTable

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('user_id')->unsigned(); 
     $table->string('title', 255); 
     $table->text('content'); 
     $table->timestamps(); 
    }); 

    Schema::table('posts', function($table) { 
     $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
    }); 
} 
+0

我試過了,但沒有發生。 –

+0

@LaravelMan如果表已創建,則需要添加新的遷移文件並在該文件中分配外鍵代碼,然後運行遷移。 –

+0

@MeeraTank我也試過了,但仍然不能正常工作 –