File tree 2 files changed +26
-0
lines changed
2 files changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -502,6 +502,14 @@ func (db *DB) Count(count *int64) (tx *DB) {
502
502
return
503
503
}
504
504
505
+ // Exists checks if there is any record matching the given conditions
506
+ func (db * DB ) Exists () (bool , error ) {
507
+ var exist bool
508
+ return exist , db .Session (& Session {NewDB : true }).
509
+ Raw ("SELECT ? AS exist" , Expr ("EXISTS(?)" , db .Select ("1" ).Limit (1 ))).
510
+ Pluck ("exist" , & exist ).Error
511
+ }
512
+
505
513
func (db * DB ) Row () * sql.Row {
506
514
tx := db .getInstance ().Set ("rows" , false )
507
515
tx = tx .callbacks .Row ().Execute (tx )
Original file line number Diff line number Diff line change @@ -1453,3 +1453,21 @@ func TestQueryScanToArray(t *testing.T) {
1453
1453
t .Error ("users[1] should be empty" )
1454
1454
}
1455
1455
}
1456
+
1457
+ func TestExists (t * testing.T ) {
1458
+ ok , err := DB .Table ("users" ).Where ("name = ?" , "jinzhu" ).Exists ()
1459
+ if err != nil {
1460
+ t .Fatalf ("Failed to scan, got %v" , err )
1461
+ }
1462
+ if ! ok {
1463
+ t .Errorf ("Should found record" )
1464
+ }
1465
+
1466
+ ok , err = DB .Table ("users" ).Where ("name = ?" , "jinzhu-jinzhu" ).Exists ()
1467
+ if err != nil {
1468
+ t .Fatalf ("Failed to scan, got %v" , err )
1469
+ }
1470
+ if ok {
1471
+ t .Errorf ("Should not found record" )
1472
+ }
1473
+ }
You can’t perform that action at this time.
0 commit comments