Home  >  Article  >  Backend Development  >  Missing fields in GORM lookup method

Missing fields in GORM lookup method

WBOY
WBOYforward
2024-02-13 20:40:091238browse

GORM 查找方法中缺少字段

php editor Xinyi sometimes encounters a problem when using GORM: in the search method, the returned results are missing some fields. This may be because we did not add a label to the field when defining the structure. In GORM, you can specify how fields are mapped in the database by using tags. Therefore, in order to solve this problem, we need to add the correct label to each field in the structure to ensure that the values ​​of all fields can be returned correctly when querying.

Question content

Trying to use the GORM method find to get the values ​​of the database table, but it does not return the values ​​of all fields. The table structure is,

CREATE TABLE `company` (
  `id` varchar(36) NOT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `name` varchar(255) NOT NULL,
  `newId` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In company.go, we define the company structure as,

package entities

import "time"

type Company struct {
    Id        string    `json:"id" gorm:"column:id;primaryKey"`
    CreatedAt time.Time `json:"createdAt" gorm:"column:createdAt"`
    UpdatedAt time.Time `json:"updatedAt" gorm:"column:updatedAt"`
    Name      string    `json:"name" gorm:"column:name"`
    NewId     string    `json:"newId" gorm:"column:newId"`
}

In the controller companies.go, use the following code to get the data,

var companys []entities.Company
    result := db.Find(&companys)
    c.JSON(http.StatusOK, &result)

In Postman, it only returns the values ​​of the fields name and id. The remaining fields have empty values. What could be the problem?

I tried to get all fields using GORM's find method but it only gives two fields

The data in the table is as follows,

Workaround

As stated in the documentation, createdAt and updatedAt are managed by GORM, so you can leave Tag gorm?

The above is the detailed content of Missing fields in GORM lookup method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete