php - Laravel迁移: pivot table role_user doesn't exist

标签 php laravel laravel-artisan

使用 Laravel 5,我正在创建一个新项目,其中 UserRole 之间具有 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/

相关文章:

php - 如何使 Laravel (Blade) 文本字段只读

javascript - 对elFinder和CKeditor整合直接上传文件

laravel - 阻止工匠询问 "Do you really wish to run this command?"

php - Laravel 未定义数组键 1 php artisan 服务

php - Exception类中的$ previous是什么?

php - Shopify API PHP : Updating a variant's attributes, 具体库存数量

php - 不将 PHP 页面呈现给 IE

Laravel 3 - 如何验证复选框数组,至少选中 1 个?

php - artisan 错误 : Failed to listen on localhost:8000

php - 你怎么匹配12小时时间 hh :mm in a regex?