久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      laravel中firstOrNew, firstOrCreate, firstOr 和 updateOrCreate 方法

      下面由Laravel開發(fā)入門教程欄目給大家介紹使用laravel中firstOrNew, firstOrCreate, firstOr 和 updateOrCreate 方法,希望對需要的朋友有所幫助!

      laravel中firstOrNew, firstOrCreate, firstOr 和 updateOrCreate 方法

      如果您曾經(jīng)使用過 Laravel ,那么您可能知道創(chuàng)建 Eloquent 模型的標(biāo)準(zhǔn)方法,例如 make(),create(),update 和 save()。 Laravel 還提供了一些大家沒有注意到的其他方法,這些方法對于創(chuàng)建和更新模型也非常有用。 因此,在本文中,我想介紹一些其他方法,并說明它們可能會有用:

      firstOrNew

      firstOrNew 方法找到第一個滿足某些約束的模型,沒有滿足約束條件的數(shù)據(jù)時 new 一個新的模型。

      您可以采用如下代碼:

      $user = User::where('email', request('email'))->first(); if ($user === null) {     $user = new User(['email' => request('email')]); } $user->name = request('name'); $user->save()

      并將其改寫成:

      $user = User::firstOrNew(['email' =>  request('email')]); $user->name = request('name'); $user->save()

      如果找不到已有的模型,您還可以通過第二個參數(shù)傳遞一個附加屬性數(shù)組:

      $user = User::firstOrNew(     ['email' =>  request('email')],     ['name' => request('name')] ); $user->save();

      firstOrCreate

      firstOrCreate 方法跟 firstOrNew 方法很相似。它會嘗試根據(jù)你傳遞的第一個參數(shù)去查找匹配的模型,如果沒找到,會自動用第二個參數(shù)傳遞的值創(chuàng)建并且保存一個新的模型:

      $user = User::firstOrCreate(     ['email' =>  request('email')],     ['name' => request('name')] ); // No call to $user->save() needed

      firstOr

      我最近摸魚的時候發(fā)現(xiàn)了 firstOr 這個方法。 firstOr 方法會檢索第一條數(shù)據(jù),如果沒有找到匹配的數(shù)據(jù),就會執(zhí)行傳入的回調(diào)。如果您在創(chuàng)建用戶時需要執(zhí)行額外的步驟,或者想要執(zhí)行除創(chuàng)建新用戶以外的其他操作,這將非常有用:

      $user = User::where('email', request('email'))->firstOr(function () {     $account = Account::create([ //... ]);     return User::create([         'account_id' => $account->id,         'email' => request('email'),      ]); });

      updateOrCreate

      updateOrCreate 方法試圖找到一個與第一個參數(shù)傳遞的約束條件匹配的模型。 如果找到匹配的模型,它將使用第二個參數(shù)傳遞的屬性更新模型。 如果找不到匹配的模型,則將創(chuàng)建一個新模型,同時將第一個參數(shù)和第二個參數(shù)傳入。

      您可以重構(gòu)這段代碼:

      $user = User::where('email', request('email'))->first(); if ($user !== null) {     $user->update(['name' => request('name')]); } else {     $user = User::create([       'email' => request('email'),       'name' => request('name'),     ]); } // Do other things with the User

      使用 updateOrCreate 方法:

      $user = User::updateOrCreate(     ['email' =>  request('email')],     ['name' => request('name')] ); // Do other things with the User

      結(jié)論

      總的來說,我認(rèn)為這些方法可以在某些情況下幫助您簡化代碼!您是否知道其他一些有用又不為人所知的小技巧, 有的話記得告訴我。 我喜歡學(xué)習(xí)這些使 Laravel 變得如此出色的小細(xì)節(jié)。

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號