目錄
?️ Basic Syntax
How it works:
? Real-World Example
? updateOrInsert vs firstOrCreate / updateOrCreate
? Key Points to Remember
✅ Pro Tip: Use with Models (but carefully)
首頁 php框架 Laravel 如何在Laravel中使用UpdateOrinsert?

如何在Laravel中使用UpdateOrinsert?

Jul 28, 2025 am 01:52 AM
laravel

updateOrInsert 是Laravel 中通過單個數據庫查詢實現“存在則更新,否則插入”的高效方法,1. 它不觸發模型事件、不自動處理時間戳、不返回模型實例;2. 需手動指定created_at 和updated_at;3. 適用於無需模型邏輯的高性能場景,如API 同步或設置更新;4. 只能用於查詢構造器,返回布爾值表示操作是否成功。

How to use updateOrInsert in Laravel?

The updateOrInsert method in Laravel is a handy way to either update a record if it exists, or insert a new one if it doesn't — without triggering model events like created or updated . It's efficient because it uses a single database query and doesn't load the model into memory.

How to use updateOrInsert in Laravel?

Here's how to use updateOrInsert properly:


✅ When to Use updateOrInsert

Use updateOrInsert when you want to:

How to use updateOrInsert in Laravel?
  • Avoid extra queries (like checking existence first)
  • Skip model events and observers
  • Perform simple upsert-like logic directly at the query builder level

?️ Basic Syntax

 DB::table('users')->updateOrInsert(
    ['email' => 'john@example.com'], // Conditions to find the record
    ['name' => 'John Doe', 'age' => 30] // Data to update or insert
);

How it works:

  • If a row exists with email = 'john@example.com' , it will be updated with the second array.
  • If no matching row is found , a new row is inserted with both the condition fields and the update fields.

So the resulting insert would be:

 INSERT INTO users (email, name, age) VALUES ('john@example.com', 'John Doe', 30);

? Real-World Example

Say you're syncing user preferences from an external service:

How to use updateOrInsert in Laravel?
 DB::table('user_preferences')->updateOrInsert(
    [
        'user_id' => 123,
        'setting_key' => 'theme',
    ],
    [
        'setting_value' => 'dark',
        'updated_at' => now(),
        // 'created_at' won't be auto-set — you must handle it manually
    ]
);

⚠️ Note: Unlike Eloquent models, updateOrInsert won't automatically set created_at or updated_at . You need to include them explicitly.

So better to do:

 $timestamps = ['created_at' => now(), 'updated_at' => now()];

DB::table('user_preferences')->updateOrInsert(
    ['user_id' => 123, 'setting_key' => 'theme'],
    ['setting_value' => 'dark', 'updated_at' => now()] $timestamps
);

? updateOrInsert vs firstOrCreate / updateOrCreate

Method Uses Model Events Returns Model Auto-manages timestamps
updateOrInsert ❌ No ❌ No (returns boolean) ❌ No
firstOrCreate / updateOrCreate ✅ Yes ✅ Yes ✅ Yes

? Use updateOrInsert for performance and simple queries .
? Use updateOrCreate when you need model events , accessors, mutators, or relationships.


? Key Points to Remember

  • Works only on the Query Builder ( DB::table() or Model::query() )
  • Returns a boolean : true on success, false on failure
  • Does not fire Eloquent events
  • Doesn't auto-fill created_at or updated_at
  • Uses raw SQL under the hood — great for bulk or background jobs

✅ Pro Tip: Use with Models (but carefully)

You can call it on a model's query builder:

 User::query()->updateOrInsert(
    ['email' => 'sarah@example.com'],
    ['name' => 'Sarah', 'updated_at' => now()]
);

Still — no events, no model booting, no casts, etc.


So, updateOrInsert is fast and lightweight, perfect for stateless operations like API syncs, counters, or preference updates.

Basically: "Find by these fields, update with these values — or insert all together if not found." And that's it.

以上是如何在Laravel中使用UpdateOrinsert?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何用PHP開發問答社區平台 PHP互動社區變現模式詳解 如何用PHP開發問答社區平台 PHP互動社區變現模式詳解 Jul 23, 2025 pm 07:21 PM

1.PHP開發問答社區首選Laravel MySQL Vue/React組合,因生態成熟、開發效率高;2.高性能需依賴緩存(Redis)、數據庫優化、CDN和異步隊列;3.安全性必須做好輸入過濾、CSRF防護、HTTPS、密碼加密及權限控制;4.變現可選廣告、會員訂閱、打賞、佣金、知識付費等模式,核心是匹配社區調性和用戶需求。

Laravel路由參數傳遞與控制器方法匹配指南 Laravel路由參數傳遞與控制器方法匹配指南 Jul 23, 2025 pm 07:24 PM

本文旨在解決Laravel框架中路由參數傳遞與控制器方法匹配的常見錯誤。我們將詳細解釋為何在路由定義中將參數直接寫入控制器方法名會導致“方法不存在”的錯誤,並提供正確的路由定義語法,確保控制器能正確接收並處理路由參數。此外,文章還將探討在刪除操作中使用HTTPDELETE方法的最佳實踐。

Laravel Livewire中動態訪問模型關聯屬性的data_get實踐 Laravel Livewire中動態訪問模型關聯屬性的data_get實踐 Jul 23, 2025 pm 06:51 PM

本文旨在解決LaravelLivewire組件中動態渲染數據時,如何通過字符串路徑高效且安全地訪問模型關聯的深層屬性。當需要根據配置字符串(如"user.name")獲取關聯模型的特定字段時,直接使用對象屬性訪問會失敗。文章將詳細介紹Laravel的data_get輔助函數,並提供代碼示例,展示如何利用它優雅地解決這一問題,確保數據獲取的靈活性和健壯性。

如何在PHP環境中設置環境變量 PHP運行環境變量添加說明 如何在PHP環境中設置環境變量 PHP運行環境變量添加說明 Jul 25, 2025 pm 08:33 PM

PHP設置環境變量主要有三種方式:1.通過php.ini全局配置;2.通過Web服務器(如Apache的SetEnv或Nginx的fastcgi_param)傳遞;3.在PHP腳本中使用putenv()函數。其中,php.ini適用於全局且不常變的配置,Web服務器配置適用於需要隔離的場景,putenv()適用於臨時性的變量。持久化策略包括配置文件(如php.ini或Web服務器配置)、.env文件配合dotenv庫加載、CI/CD流程中動態注入變量。安全管理敏感信息應避免硬編碼,推薦使用.en

如何用PHP開發AI智能表單系統 PHP智能表單設計與分析 如何用PHP開發AI智能表單系統 PHP智能表單設計與分析 Jul 25, 2025 pm 05:54 PM

選擇合適的PHP框架需根據項目需求綜合考慮:Laravel適合快速開發,提供EloquentORM和Blade模板引擎,便於數據庫操作和動態表單渲染;Symfony更靈活,適合複雜系統;CodeIgniter輕量,適用於對性能要求較高的簡單應用。 2.確保AI模型準確性需從高質量數據訓練、合理選擇評估指標(如準確率、召回率、F1值)、定期性能評估與模型調優入手,並通過單元測試和集成測試保障代碼質量,同時持續監控輸入數據以防止數據漂移。 3.保護用戶隱私需採取多項措施:對敏感數據進行加密存儲(如AES

如何讓PHP容器支持自動構建 PHP環境持續集成CI配置方式 如何讓PHP容器支持自動構建 PHP環境持續集成CI配置方式 Jul 25, 2025 pm 08:54 PM

要讓PHP容器支持自動構建,核心在於配置持續集成(CI)流程。 1.使用Dockerfile定義PHP環境,包括基礎鏡像、擴展安裝、依賴管理和權限設置;2.配置GitLabCI等CI/CD工具,通過.gitlab-ci.yml文件定義build、test和deploy階段,實現自動構建、測試和部署;3.集成PHPUnit等測試框架,確保代碼變更後自動運行測試;4.使用Kubernetes等自動化部署策略,通過deployment.yaml文件定義部署配置;5.優化Dockerfile,採用多階段構

Laravel 路由參數傳遞:正確定義控制器方法與路由綁定 Laravel 路由參數傳遞:正確定義控制器方法與路由綁定 Jul 23, 2025 pm 07:06 PM

本文深入探討Laravel路由中控制器方法參數傳遞的正確姿勢。針對常見的將路由參數直接寫入控制器方法名導致的錯誤,詳細闡述了正確的路由定義語法,並強調了Laravel自動參數綁定的機制。同時,文章建議使用更符合RESTful規範的HTTPDELETE方法處理刪除操作,以提升應用的可維護性和語義化。

Laravel的編寫單元和功能測試。 Laravel的編寫單元和功能測試。 Jul 23, 2025 am 02:38 AM

themaindifferenceBeteNInitAndAndFeateTestsInlaraveSthatunIttestSfocusOnisolatedComponentsLikeClassEsesemementemementementsormethods,whileFeatureTestestSsssSssSerusteSeruseSerInteractions.unitTestScheckInternTernTernTernTernTernTernallogicSuchAsamEthogicSuchAdeTurningThecorRectValueTheCorrectValue,areSeSford and doffore,andDonteveve

See all articles