updateOrCreate()给出未找到的列:1054“ where子句”中的未知列“ 0”

时间:2018-09-06 14:16:56

标签: php mysql laravel laravel-5

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

  

SQLSTATE [42S22]:找不到列:1054'where中的未知列'0'   子句”(SQL:从roles中选择*,其中{0 = user_id和1 = =   并且2 = 10)限制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");
});

RegisterController

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"]);
}

我该如何解决?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:3)

必须使用关联数组设置值,其中列名是键,而值是要查找/插入的值。

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