SQLSTATE [42S22]:找不到列:1054未知列Laravel

时间:2015-09-12 09:40:55

标签: join laravel-5 roles

当我想将角色与用户结合时,我收到此错误:

  

SQLSTATE [42S22]:未找到列:1054未知列' roles_id'在'字段列表' (SQL:插入roles_usercreated_atroles_idupdated_atuser_id)值(2015-09-12 09:37:35,2, 2015-09-12 09:37:35,1))

这是我的角色迁移:

    public function up()
{
    Schema::create('roles',function (Blueprint $table){
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });

    DB::table('roles')->insert(array(
        array('name' => 'user'),
        array('name' => 'admin'),
        ));
}

这是我的用户迁移:

 public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('roles_id')->unsigned();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}

这是我的支点表:

 public function up()
{
    Schema::create('roles_user',function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('role_id')->unsigned()->index();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });
}

在我的角色模型中,我说:

public function roles()
{
    return $this->belongsToMany('App\roles')->withTimestamps();
} here

1 个答案:

答案 0 :(得分:1)

首先,我不知道你为什么

$table->integer('roles_id')->unsigned();

users表格中?如果您希望每个用户只有一个角色,那就是这种情况。但是你的多对多关系表明你需要一个用户才能拥有多个角色。所以我会摆脱这条线。

然后,belongsToMany关系应该采用Role模型,而不是模型表。

class Role extends Model {
    protected $table = 'roles';
}

class User extends Model {
    protected $table = 'users';

    public function roles()
    {
        return $this->belongsToMany('App\Role')->withTimestamps();
    }
}
相关问题