使用 Laravel 5,我正在创建一个新项目,其中 User
和 Role
之间具有 n:n
关系。
当我清空数据库并键入命令: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');
}
}
最佳答案
Schema::table('role_user', function (Blueprint $table) {
应该是
Schema::create('role_user', function (Blueprint $table) {
请注意更改:table
已更改为 create
,因为您正在创建此表,而不是更改它,您无法更改不存在的内容:)
迁移也称为 CreateRoleUserTable
,因此表明它是创建而不是更改。
关于php - Laravel迁移: pivot table role_user doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43298581/