feature: add exists method

This commit is contained in:
demoManito 2024-09-30 18:28:30 +08:00
parent 62bd0b9331
commit 780e1797a6
2 changed files with 28 additions and 0 deletions

View File

@ -502,6 +502,12 @@ func (db *DB) Count(count *int64) (tx *DB) {
return
}
// Exists checks if there is any record matching the given conditions
func (db *DB) Exists() (bool, error) {
var exists bool
return exists, db.Session(&Session{NewDB: true}).Raw("SELECT ?", Expr("EXISTS(?)", db.Select("1"))).Pluck("exists", &exists).Error
}
func (db *DB) Row() *sql.Row {
tx := db.getInstance().Set("rows", false)
tx = tx.callbacks.Row().Execute(tx)

View File

@ -1453,3 +1453,25 @@ func TestQueryScanToArray(t *testing.T) {
t.Error("users[1] should be empty")
}
}
func TestExists(t *testing.T) {
if DB.Dialector.Name() == "sqlserver" {
t.Skip()
}
ok, err := DB.Table("users").Where("name = ?", "jinzhu").Exists()
if err != nil {
t.Fatalf("Failed to scan, got %v", err)
}
if !ok {
t.Errorf("Should found record")
}
ok, err = DB.Table("users").Where("name = ?", "jinzhu-jinzhu").Exists()
if err != nil {
t.Fatalf("Failed to scan, got %v", err)
}
if ok {
t.Errorf("Should not found record")
}
}