【问题标题】:SQLSTATE[42S22]: Column not found: 1054 Unknown column LaravelSQLSTATE [42S22]:找不到列:1054 未知列 Laravel
【发布时间】:2015-12-08 20:01:33
【问题描述】:

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

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

【问题讨论】:

    标签: join laravel-5 roles


    【解决方案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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2018-11-02
      • 2019-10-02
      • 2017-04-03
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      相关资源
      最近更新 更多