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

How to query data where column is not null in gorm

这是我的两个模型,我想让我的代码return所有里面有节点的路径,排除所有里面没有节点的路径

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)

您可以添加一个额外的 INNER JOIN 以仅加载具有节点的路径。它看起来像这样:

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