英文:
DB Query Commands are producing strange sql queries
问题
我有一个模型如下:
type Report struct {
ID int `json:"id,omitempty" gorm:"primary_key"`
Title *string `json:"title" gorm:"not null"`
}
我已经将变量report
初始化为var report Report
,我已经成功将这个模型自动迁移为数据库表,并使用GORM的db.Create(&report)
方法填充了数据库。
我遇到的问题是在尝试查询命令时。每个GORM支持的查询命令,如db.Find(&report)
,db.First(&report, 1)
,都会导致以下查询:
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT 0 done
我无法查询数据库。我正在使用GORM与Cockroach DB。当使用GO pq驱动程序和原始的SQL命令时,这个问题没有出现。
英文:
I have my model as:
type Report struct {
ID int `json:"id,omitempty" gorm:"primary_key"`
Title *string `json:"title" gorm:"not null"`
}
I have initialized variable report
as var report Report
I have successfully auto migrated this model as database table and have populated database as sql INSERT
using GORM's db.Create(&report)
.
The problem I am facing is while trying query commands. Every query commands supported by GORM such as db.Find(&report)
, db.First(&report, 1)
is resulting to queries such as folows:
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT 0 done
I am unable to query database. I am using GORM with cockroach db. This works fine when using GO pq driver and raw sql commands.
答案1
得分: 2
deleted_at
列是GORM的基本gorm.Model
结构体的一部分,它提供了软删除功能。在这个示例中,你是否在某个地方使用了gorm.Model
?除非你定义了一个名为DeletedAt
的字段或在模型结构体中嵌入了gorm.Model
,否则不应该出现这种情况。
英文:
The deleted_at
column is a part of GORM's base gorm.Model
struct and its soft delete feature. Are you using gorm.Model
somewhere that we can't see in this example? This isn't supposed to happen unless you either define a field named DeletedAt
or embed a gorm.Model
in your model struct.
答案2
得分: 1
由于模型具有deleted_at字段,gorm会自动使用软删除功能。您可以使用Unscoped
方法:
db.Unscoped().Find(&reports)
这与运行原始查询相同:
db.Raw("SELECT * FROM reports").Scan(&reports)
英文:
Since the model has the field deleted_at, gorm is using the soft delete ability automatically. You can use Unscoped
db.Unscoped().Find(&reports)
Which is the same as running the raw query
db.Raw("SELECT * FROM reports").Scan(&reports)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论