首页 > 解决方案 > updateOrCreate() 给出 Column not found: 1054 Unknown column '0' in 'where 子句'

问题描述

我正在尝试在用户尝试时为其分配角色。但它给了我这个错误。我正在使用updateOrCreate(),因为我想稍后使用该方法来更改用户角色

SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'0'(SQL:select * from roleswhere ( 0= user_id and 1= = and 2= 10) limit 1)

Schema::create('roles', function (Blueprint $table) {
     $table->increments('id');
     $table->unsignedInteger("user_id")->index();
     $table->string("role_name");
     $table->foreign("user_id")->references("id")->on("users")->onDelete("cascade");
});

注册控制器

protected function create(array $data)
{
    $user = user::create([
        'name' => $data['name'],
        'email' => $data['email'],
        "username" => $data["username"],
        'password' => Hash::make($data['password']),
    ]);

    if ($user) {
        $model = new Role();
        $model->assignNewbieRole($user->id);
    }

    return $user;
}

好榜样

public function assignNewbieRole($id)
{
    $this->updateOrCreate(["user_id","=",$id],["role_name","=","newbie"]);
}

我该如何解决 ?

标签: phpmysqllaravellaravel-5

解决方案


您需要传递关联的数组而不是单个值:

$this->updateOrCreate(["user_id" => $id], ["role_name" => "newbie"]);

推荐阅读