开发过程中,看到同事的代码写了这么一段:
db = db.Session(&gorm.Session{Context: db.Statement.Context}).FirstOrCreate(&entity)
if db.Error !=nil{
return components.ErrorDbInsert.WrapPrintf(db.Error, "Insert error, entity:%s", utils.ToJson(entity))
}
if db.RowsAffected == 0 {
return components.ErrorAlreadyExist
}
我不禁感到疑惑, gorm
的 RowsAffected
在进行查询,如果查到数据,也是有值的,为什么在这里可以用 RowsAffected == 0
来判断数据已存在?
抱着这个疑问,我点开了 FirstOrCreate
的代码:
```go
func (db DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx DB) {
queryTx := db.Limit(1).Order(clause.OrderByColumn{
Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},