Search code examples
gogo-gorm

Fields are missing in GORM find method


Trying to get the value of the database table using the GORM method find, but it is not returning the values of all fields. 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 the company.go, we have defined 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, the data is fetched using the following code,

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

In the postman, it is only returning the values for the fields name and id. The rest of the fields the value is empty. What could be the issue?

I tried to fetch all the fields using find method of GORM, but it is only giving two fields

The data in the table looks like the following, enter image description here


Solution

  • As the document said, the createdAt and updatedAt is managed by GORM, so could you leave its gorm tags?

    CreatedAt and UpdatedAt are special fields that GORM automatically populates with the current time when a record is created or updated.