
php小编西瓜为你介绍一种高效的数据获取方法——Gorm。Gorm是一个基于Golang的ORM库,它可以轻松地与数据库交互。在使用Gorm时,我们可以根据嵌套表的条件从表中获取所有数据,无需繁琐的手动查询。这种方法不仅简化了代码,还提高了查询效率,让开发人员更加便捷地操作数据。无论是初学者还是有经验的开发者,都可以通过使用Gorm轻松地实现数据获取功能。
我有一个带有如下 golang 结构的表:
order {
id
transactionid
transaction
}
transaction {
id
profileid
profile
}
profile {
id
accountid
account
}如何通过gorm获取所有带有账户id条件的订单? 我已经尝试过:
var orders []*Order
res := r.db.
Joins("Transaction").
Preload("Transaction.Profile").
Where("Transaction.Profile.account_id = 1").
Find(&orders)但是它不起作用。
该解决方案应该基于您提供的结构定义来工作。首先,让我展示代码,然后我将完成每个步骤:
package main
import (
"fmt"
_ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Order struct {
Id int
TransactionId int
Transaction Transaction
}
type Transaction struct {
Id int
ProfileId int
Profile Profile
}
type Profile struct {
Id int
AccountId int
Account Account
}
type Account struct {
Id int
}
func main() {
dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&Account{})
db.AutoMigrate(&Profile{})
db.AutoMigrate(&Transaction{})
db.AutoMigrate(&Order{})
db.Create(&Account{})
db.Create(&Profile{AccountId: 1})
db.Create(&Transaction{ProfileId: 1})
db.Create(&Order{TransactionId: 1})
// order + transaction + profile + account
var order Order
db.Debug().Preload("Transaction.Profile.Account").Joins("inner join transactions t on orders.transaction_id = t.id").Joins("inner join profiles p on p.id = t.profile_id").Joins("inner join accounts a on p.account_id = a.id").First(&order, "a.id = ?", 1)
fmt.Println(order)
}
让我们仔细看看代码。
这里没有任何改变。声明结构时,请务必了解 gorm 约定,因为 gorm 将基于此创建关系、外键和约束。
在这里,您可以找到与 postgres 的连接、用于同步表的自动迁移命令以及一些虚拟数据的插入。
这里,我们使用了 go 的 gorm 包提供的很多方法。让我们在一个简短的列表中回顾一下它们:
debug:它将原始 sql 查询打印到控制台。处理复杂查询时非常有用preload:加载相关实体,但不将它们包含在 gorm 生成的最终查询中joins:它指定在 join 子句中必须引用哪些表。使用 joins 我们将该子句添加到查询中。first:它既用于仅获取一条记录,也用于指定一些过滤器,例如我们的例子(例如 a.id = ?)。如果这可以解决您的问题,请告诉我,谢谢!
以上就是Gorm 根据嵌套表的条件从表中获取所有数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号