gpt4 book ai didi

go - 获取数据库中的所有项目

转载 作者:行者123 更新时间:2023-12-01 22:25:23 25 4
gpt4 key购买 nike

我正在尝试使用gorm从我的数据库中获取一系列项目,它工作正常,并且能够检索数据,但是我在阵列中仅获取了一项,但还有更多。这是我检索数组的代码。

Model.go

type Address struct {
ID uuid.UUID `json:"id" gorm:"primary_key;unique;not null"`
Line string `gorm:"size:255;not null;column:line" json:"line"`
Hostel string `gorm:"size:255;not null;column:hostel" json:"hostel"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:createdAt" json:"createdAt"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:updatedAt" json:"updatedAt"`
DeletedAt *time.Time `sql:"index;column:deletedAt" json:"deletedAt"`
}

type Addresses []Address

Database.go
type DbAddress struct {
*model.Address
}

func (address *DbAddress) Get(db *gorm.DB) ([]model.Address, *errors.Error) {
var err error
addr := []model.Address{}
err = db.Debug().Model(model.Address{}).Limit(100).Take(&addr).Error
if gorm.IsRecordNotFoundError(err) {
return nil, errors.NewNotFoundError(fmt.Sprintf("Address not found: %s", err.Error()))
}
if err != nil {
return nil, errors.NewBadRequestError(fmt.Sprintf("error when trying to get Address: %s", err.Error()))
}
return addr, nil
}

Services.go
func GetAddress() (model.Addresses, *errors.Error) {
result := database.DbAddress{Address: &model.Address{}}

return result.Get(database.DB)
}

Controller.go
func GetAddress(c *gin.Context) {

address, getErr := services.GetAddress()
if getErr != nil {
res.ResponseJSON(c, getErr.Status, nil, true, getErr.Message)
return
}
res.ResponseJSON(c, http.StatusFound, address, false, "successfully got address data")
}

最佳答案

使用 Find 而不是cotija。

// Get first record, order by primary key
db.First(&user)
//// SELECT * FROM users ORDER BY id LIMIT 1;

// Get one record, no specified order
db.Take(&user)
//// SELECT * FROM users LIMIT 1;

// Get last record, order by primary key
db.Last(&user)
//// SELECT * FROM users ORDER BY id DESC LIMIT 1;

// Get all records
db.Find(&users)
//// SELECT * FROM users;

// Get record with primary key (only works for integer primary key)
db.First(&user, 10)
//// SELECT * FROM users WHERE id = 10;
有关更多详细信息,请参见: Take

关于go - 获取数据库中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60264737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com