【问题标题】:Laravel migration: pivot table role_user doesn't existLaravel 迁移:数据透视表 role_user 不存在
【发布时间】:2017-09-04 01:06:11
【问题描述】:

使用 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');
    }
}

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


    【解决方案1】:
    Schema::table('role_user', function (Blueprint $table) {
    

    应该是

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

    注意更改:table 已更改为 create,因为您正在创建此表,而不是更改它,您无法更改不存在的内容 :)

    迁移也称为CreateRoleUserTable,因此表明它是创造而不是改变。

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2020-09-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多