简体   繁体   English

如何正确使用updateOrCreate

[英]How to use updateOrCreate proprely

Here is my code : 这是我的代码:

$user = \App\User::where('id', $uid)->firstOrFail();

$user->token()->updateOrCreate(['user_id' => $uid, 'type' => $type], [
        'auth'      => $auth_token, 
        'refresh'   => $refresh_token,
        'type'      => $type
]);

I've got two models User and Token with an 'one to one' relationship. 我有两个模型UserToken ,具有'一对一'的关系。

On the first line, I try to catch a User into the database, then I update my model with the updateOrCreate() method. 在第一行,我尝试将User捕获到数据库中,然后使用updateOrCreate()方法更新我的模型。

However, as you can read it, I must use a selector 'user_id' => $uid before to successfully update my model. 但是,正如您可以阅读它,我必须使用选择器'user_id' => $uid才能成功更新我的模型。 I think Eloquent should be able to manage it in a different way without making two requests. 我认为Eloquent应该能够以不同的方式管理它,而无需提出两个请求。

You don't have to use the user_id => $uid on that query. 您不必在该查询上使用user_id => $ uid。 It's injected based on the relationship already. 它是根据已经存在的关系注入的。 You can rewrite that to: 您可以将其重写为:

    $token = \App\User::where('id', $uid)->firstOrFail()->token()->updateOrCreate(['type' => $type], [
            'auth'      => $auth_token, 
            'refresh'   => $refresh_token,
            'type'      => $type
    ]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM