2017-04-08 120 views
1

使用Laravel 5,我在UserRole之間創建了一個n:n關係的新項目。Laravel遷移:數據透視表role_user不存在

當我清空數據庫,鍵入命令:php artisan migrate:install(工作),其次是:php artisan migrate,我得到以下錯誤:

[Illuminate\Database\QueryException] 
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'manon.role_user' doesn't exist 
(SQL: alter table `role_user` add `user_id` int not null, add `role_id` int not null) 

[PDOException] 
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'manon.role_user' doesn't exist 

我被this教程啓發。

下面是一些代碼簡單位:

在Role.php:

public function users() 
{ 
    return $this->belongsToMany('User'); 
} 

在user.php的:

public function roles() 
{ 
    return $this->belongsToMany('Role'); 
} 

角色遷移:

class CreateRolesTable extends Migration 
{ 
    public function up() 
    { 
     Schema::create('roles', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('name'); 
     }); 
    } 

    public function down() 
    { 
     Schema::dropIfExists('roles'); 
    } 
} 

角色用戶遷移:

class CreateRoleUserTable extends Migration 
{ 
    public function up() 
    { 
     Schema::table('role_user', function (Blueprint $table) { 
      $table->integer('user_id'); 
      $table->integer('role_id'); 
     }); 
    } 

    public function down() 
    { 
     Schema::dropIfExists('role_user'); 
    } 
} 

用戶遷移:

class CreateUsersTable extends Migration 
{ 
    public function up() 
    { 
     Schema::create('users', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('firstName'); 
      $table->string('lastName'); 
      $table->string('email')->unique(); 
      $table->string('password'); 
      $table->rememberToken(); 
      $table->timestamps(); 
     }); 
    } 

    public function down() 
    { 
     Schema::dropIfExists('users'); 
    } 
} 

回答

2
Schema::table('role_user', function (Blueprint $table) { 

應該

Schema::create('role_user', function (Blueprint $table) { 

注意的變化:table已更改爲create爲你創建這個表,而不是改變它,你不能改變不存在的東西:)

該遷移也稱爲CreateRoleUserTable,因此表示它不是一個改動。