简体   繁体   中英

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.

On the first line, I try to catch a User into the database, then I update my model with the updateOrCreate() method.

However, as you can read it, I must use a selector 'user_id' => $uid before to successfully update my model. I think Eloquent should be able to manage it in a different way without making two requests.

You don't have to use the user_id => $uid on that query. 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
    ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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