From 06ebac640705689b606d24a6e5cb13de2978cb2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flc=E3=82=9B?= Date: Mon, 13 Mar 2023 12:54:44 +0800 Subject: [PATCH] feat: add `When` --- chainable_api.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/chainable_api.go b/chainable_api.go index a85235e0..d51da9d2 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -205,6 +205,20 @@ func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) { return } +// When add conditions when condition is true +// +// // Find the first user with name jinzhu +// db.When(true, func(db *gorm.DB) *gorm.DB { +// return db.Where("name = ?", "jinzhu") +// }).First(&user) +func (db *DB) When(condition bool, fn func(*DB) *DB) *DB { + if condition { + return fn(db) + } + + return db +} + // Not add NOT conditions // // Not works similarly to where, and has the same syntax.