我正在尝试使用它从我的数据库中获取一组项目,gorm它工作正常,我能够检索数据,但我只在数组中获取一个项目,而还有更多。这是我检索数组的代码。
模型.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
数据库.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
}
服务.go
func GetAddress() (model.Addresses, *errors.Error) {
result := database.DbAddress{Address: &model.Address{}}
return result.Get(database.DB)
}
控制器.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")
}
交互式爱情
相关分类