feature: add exists method
This commit is contained in:
parent
62bd0b9331
commit
780e1797a6
@ -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)
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user