php 如果记录存在则 Laravel 更新,如果不存在则创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33139076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:23:30  来源:igfitidea点击:

Laravel Update if record exists or Create if not

phplaravellaravel-5

提问by ssuhat

I want to update my record if it exists but create new one if not exists. here is i got so far:

我想更新我的记录(如果存在),但如果不存在则创建新记录。这是我到目前为止:

 MerchantBranch.php
public function token()
{
   return $this->hasOne('App\MerchantBranchToken');
}

MerchantBranchToken.php
public function merchant_branch()
{
   return $this->belongsTo('App\MerchantBranch');
}

$find = MerchantBranchToken::find($id);

    if (!$find) {
        $branch = new MerchantBranchToken(['token' => $token]);
        MerchantBranch::find($id)->token()->save($branch);
    } else {
        $find->token = $token;
        $find->save();
    }  

It's working perfectly.

它工作得很好。

But as i know Laravel is very powerful for its eloquent model. Can I make it shorter? or i already doing it correctly?.

但据我所知,Laravel 的雄辩模型非常强大。我可以缩短它吗?还是我已经做对了?

I've tried using "updateOrCreate" method but my foreign key "merchant_branch_id" need to be fillable.

我试过使用“updateOrCreate”方法,但我的外键“merchant_branch_id”需要可填充。

回答by tuananh

Laravel provide method updateOrCreatefor that purpose

Laravel提供方法updateOrCreate为目的

  • If there's a flight from Oakland to San Diego, set the price to $99.

  • If no matching model exists, create one.

  • 如果有从奥克兰飞往圣地亚哥的航班,请将价格设置为 99 美元。

  • 如果不存在匹配的模型,则创建一个。

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

回答by Safoor Safdar

Laravel already using this methodology by savefunction

Laravel 已经按save功能使用了这种方法

$user->save()

Laravel Code

Laravel 代码

// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists)
{
    $saved = $this->performUpdate($query);
}

// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the database.
else
{
    $saved = $this->performInsert($query);
}

https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L1491

https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L1491

->exists

->exists

All laravel models have a ->existsproperty.

所有 Laravel 模型都有一个->exists属性。

More specifically if the model is either loaded from the database, or has been saved to the database since being created the existsproperty will be true; Otherwise it will be false.

更具体地说,如果模型是从数据库加载的,或者自创建以来已保存到数据库中,则该exists属性将为真;否则会是假的。

If you understand the ->existsyou can use it but here is the another way to deal such requirement.

如果您了解->exists您可以使用它,但这是处理此类要求的另一种方法。

another way.

其它的办法。

/**
     * Create or update a record matching the attributes, and fill it with values.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return static
     */
    public static function updateOrCreate(array $attributes, array $values = array())
    {
        $instance = static::firstOrNew($attributes);

        $instance->fill($values)->save();

        return $instance;
    }

回答by kamran karimi

Add new function code :

添加新的功能代码:

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php :

供应商/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php :

  public function updateOrInsert(array $attributes, array $values = [])
    {
        $instance = $this->where($attributes);
        if ($instance->count() != 0) {
            $instance->update($values);
        } else {
            $instance = $this->updateOrCreate($attributes, $values);
        }
        return $instance;
    }