如何在 GORM 中查询列不为空的数据?

huangapple go评论83阅读模式
英文:

How to query data where column is not null in gorm

问题

这是我的两个模型,我希望我的代码返回所有包含节点的路径,并排除所有不包含节点的路径。

type Path struct {
	gorm.Model
	ID          uuid.UUID `json:"id" gorm:"type:uuid;primary_key"`
	Name        string    `json:"name" gorm:"type:varchar(255)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	UserID      uuid.UUID `json:"user_id" gorm:"type:uuid"`
	Owner       User      `json:"owner" gorm:"foreignKey:UserID"`
	Nodes       []Node    `gorm:"foreignKey:PathID"`
}

type Node struct {
	gorm.Model
	ID          uuid.UUID `json:"_id" gorm:"type:uuid;primary_key"`
	Name        string    `json:"name" gorm:"type:varchar(255)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Url         string    `json:"url" gorm:"required"`
	Nodetype    string    `json:"nodetype" gorm:"type:varchar(255)"`
	PathID      uuid.UUID `json:"path_id" gorm:"type:uuid"`
	Path        Path      `gorm:"foreignKey:PathID"`
}

func (path *Path) BeforeCreate(tx *gorm.DB) (err error) {
	// UUID version 4
	path.ID = uuid.New()
	return
}

func (node *Node) BeforeCreate(tx *gorm.DB) (err error) {
	// UUID version 4
	node.ID = uuid.New()
	return
}

我想获取所有具有节点的路径。

我尝试了以下方法,但没有起作用。

func GetAllPaths(c *fiber.Ctx) error {
	db := database.DB

	paths := []models.Path{}

	err := db.Debug().Joins("Owner").Preload("Nodes").Where("nodes IS NOT NULL").Find(&paths).Error
	if err != nil {
		return c.Status(500).SendString(err.Error())
	}

	var allPaths []serializer.PathResponseStruct

	for _, path := range paths {
		rpath := serializer.PathResponse(path)
		allPaths = append(allPaths, rpath)
	}

	return c.Status(200).JSON(allPaths)
}

我希望得到的响应是包含节点的路径数组,而不是空的节点数组(null)。

英文:

Here is my two models, I want to have my code return all the paths which has nodes inside them, and exclude all the path which has no nodes inside them

type Path struct {
	gorm.Model
	ID          uuid.UUID `json:"id" gorm:"type:uuid;primary_key"`
	Name        string    `json:"name" gorm:"type:varchar(255)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	UserID      uuid.UUID `json:"user_id" gorm:"type:uuid"`
	Owner       User      `json:"owner" gorm:"foreignKey:UserID"`
	Nodes       []Node    `gorm:"foreignKey:PathID"`
}

type Node struct {
	gorm.Model
	ID          uuid.UUID `json:"_id" gorm:"type:uuid;primary_key"`
	Name        string    `json:"name" gorm:"type:varchar(255)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Url         string    `json:"url" gorm:"required"`
	Nodetype    string    `json:"nodetype" gorm:"type:varchar(255)"`
	PathID      uuid.UUID `json:"path_id" gorm:"type:uuid"`
	Path        Path      `gorm:"foreignKey:PathID"`
}

func (path *Path) BeforeCreate(tx *gorm.DB) (err error) {
	// UUID version 4
	path.ID = uuid.New()
	return
}

func (node *Node) BeforeCreate(tx *gorm.DB) (err error) {
	// UUID version 4
	node.ID = uuid.New()
	return
}

I want to fetch all the paths available with nodes

I have tried with this approach but not working

func GetAllPaths(c *fiber.Ctx) error {
	db := database.DB

	paths := []models.Path{}

	err := db.Debug().Joins("Owner").Preload("Nodes").Where("nodes IS NOT NULL").Find(&paths).Error
	if err != nil {
		return c.Status(500).SendString(err.Error())
	}

	var allPaths []serializer.PathResponseStruct

	for _, path := range paths {
		rpath := serializer.PathResponse(path)
		allPaths = append(allPaths, rpath)
	}

	return c.Status(200).JSON(allPaths)
}

The response I want is array paths with nodes, not empty array of nodes (null)

答案1

得分: 0

你可以添加一个额外的INNER JOIN来加载只有节点的路径。代码如下所示:

paths := []models.Path{}
err := db.Debug().Preload("Owner").Preload("Nodes").    //如果你想加载节点内的路径,应该使用.Preload("Nodes.Path")
          Joins("INNER JOIN nodes ON nodes.path_id = paths.id").Find(&paths).Error
英文:

You could add an additional INNER JOIN to load only paths that have nodes. It would look something like this:

paths := []models.Path{}
err := db.Debug().Preload("Owner").Preload("Nodes").    //if you want to load the Path inside the node, then it should be .Preload("Nodes.Path")
          Joins("INNER JOIN nodes ON nodes.path_id = paths.id").Find(&paths).Error

huangapple
  • 本文由 发表于 2022年3月8日 16:57:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/71392344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定