Laravel如果记录存在则更新,如果不存在则创建 [英] Laravel Update if record exists or Create if not

查看:502
本文介绍了Laravel如果记录存在则更新,如果不存在则创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新我的记录(如果存在),但是如果不存在则创建一个新记录.这是我到现在为止:

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();
    }  

工作正常.

但是据我所知,Laravel的雄辩模型非常强大. 我可以把它缩短吗?还是我已经正确执行了?.

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

我尝试使用"updateOrCreate"方法,但是我的外键"merchant_branch_id"必须可填写.

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

推荐答案

Laravel提供方法

Laravel provide method updateOrCreate for that purpose

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

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

如果不存在匹配的模型,请创建一个.

If no matching model exists, create one.

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

这篇关于Laravel如果记录存在则更新,如果不存在则创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆