【发布时间】:2017-09-04 01:06:11
【问题描述】:
使用 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');
}
}
role_user 迁移:
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');
}
}
【问题讨论】:
标签: php laravel laravel-artisan