登录
首页 >  Golang >  Go问答

Not()是一个无效的函数

来源:stackoverflow

时间:2024-03-25 13:42:31 458浏览 收藏

使用 GORM 查询时遇到“Not() 是一个无效的函数”错误,这是因为使用的是 MySQL 数据库,但导入的所有方言包都会调用各自的回调,注册特定于方言的回调。要解决此问题,可以从导入中删除所有不使用的方言,并使用 Where() 方法的 not in 参数来指定条件。

问题内容

我使用的是go版本go1.10.3 linux/amd64和mysql 5.7。

需要使用 gorm 的 docker compose 配置运行,或者请提供您的配置。

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mssql"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    _ "github.com/jinzhu/gorm/dialects/postgres"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

var db *gorm.DB

func init() {
    var err error

     db, err = gorm.Open("mysql", "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True")

    if err != nil {
        panic(err)
    }
    db.LogMode(true)
}

type Res {
    Id int  `gorm:"column:id"`
    age int  `gorm:"column:age"`
}

func main() {
        var result []Res
    db.Table("A").Select("A.id,A.age").Joins("left join B on A.id=B.id").
        Where("A.age=28").
       Not("B.id", []{2,3,4,5}).
       Scan(&result)
       fmt.Printf("%v", result)
}

sql日志是:

select a.id,a.age from a left join b on a.id=b.id where a.age=28 and a.b.id not in(2,3,4,5)

可以看出,对表a追加了not操作(a.b.id not in ...)。如何将其附加到表 b(b.id 不在 ... 中)?


解决方案


首先,根据我的评论:您仅使用 mysql 作为数据库,但您正在导入所有方言包(它们确实调用各自的 init 函数。这些函数注册特定于方言的回调(例如 the MsSQL package 中的 init 函数)。从导入中删除所有不使用的方言:

// remove lines that i've commented out here...
import (
    "github.com/jinzhu/gorm"
    // _ "github.com/jinzhu/gorm/dialects/mssql"
     _ "github.com/jinzhu/gorm/dialects/mysql"
    // _ "github.com/jinzhu/gorm/dialects/postgres"
    // _ "github.com/jinzhu/gorm/dialects/sqlite"
)

您可以将 where 子句的 not in 部分移至基于 the documentationjoin 条件。

我还会检查您可能遇到的任何错误,它们可能会在日志顶部为您提供更多调试信息:

err := db.table("a").select("a.id,a.age").
    joins("left join b on a.id =  b.id and b.id not in (?)", []int{2, 3, 4, 5}).
    where("age = ?", 28).
    scan(&result).error
if err != nil {
    fmt.fatalf("failed to execute query: %+v", err)
}
fmt.prinln(result)

已解决

使用

Where("B.id not in(?)", [] {2,3,4,5}) instead of Not()

有人有更好的主意吗?

今天关于《Not()是一个无效的函数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>