Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select exists with GORM

Tags:

go

exists

go-gorm

I want to check if a row exists in a database table or not. I first used this approach:

type MyStruct struct {
    ID    uint32
    Key   string
    Value string
}

var result MyStruct

err := db.
    Where("id = ? AND `key` = ? AND `value` = 0", myID, myKey).
    First(&result).
    Error

if err != nil {
    if err == gorm.ErrRecordNotFound {
        logrus.Error("ErrRecordNotFound")
    }
    logrus.Errorf("Other DB error: %s", err.Error())
}

But I want to achieve this by writing a raw SQL. I tried following:

var result bool

db.Raw("SELECT EXISTS(SELECT 1 FROM my_table WHERE id = ? AND `key` = ? AND `value` = ?)",
    myID, myKey, "0").Scan(&result)

But I get this error:

unsupported destination, should be slice or struct.

I also tried to use method Exec and got the same error.

Note that the variable db is a *gorm.DB instance.

like image 337
Zeinab Abbasimazar Avatar asked Feb 17 '26 03:02

Zeinab Abbasimazar


1 Answers

You can try the following approach

var exists bool
err = db.Model(model).
         Select("count(*) > 0").
         Where("id = ?", id).
         Find(&exists).
         Error
like image 154
VlasovArtem Avatar answered Feb 18 '26 18:02

VlasovArtem