Missing fields in GORM lookup method

WBOY
Release: 2024-02-13 20:40:09
forward
1208 people have browsed it

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;
Copy after login

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"`
}
Copy after login

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)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!