1
使用Laravel 5,我在User
和Role
之間創建了一個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');
}
}