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

SQLSTATE[42S22]: Column not found: 1054 Unknown column Laravel

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

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles_id' in 'field list' (SQL: insert into roles_user (created_at, roles_id, updated_at, user_id) values (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();
    });
}

这是我的支点table:

 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

首先,我不知道你为什么要

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

在你的userstable?这是为了防止您希望每个用户拥有一个且只有一个角色。但是这里的多对多关系表明您需要一个用户能够拥有多个角色。所以我会去掉这一行。

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

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

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

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