获取数据库中的所有项目

我正在尝试使用它从我的数据库中获取一组项目,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")

}


汪汪一只猫
浏览 75回答 1
1回答

交互式爱情

使用Find而不是Take.// Get first record, order by primary keydb.First(&user)//// SELECT * FROM users ORDER BY id LIMIT 1;// Get one record, no specified orderdb.Take(&user)//// SELECT * FROM users LIMIT 1;// Get last record, order by primary keydb.Last(&user)//// SELECT * FROM users ORDER BY id DESC LIMIT 1;// Get all recordsdb.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;有关更多详细信息,请参阅:https ://gorm.io/docs/query.html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go