duandun2136 2019-05-02 12:22
浏览 2644

gorm:加入变化多端的“ where”条件

I have 2 tables: Actors and Films. I need to get actors with all their films by changeable filters - they can be present or absent, a single value or a slice of possible values.

I suspect that the way I made it work (with the db object) smells bad.

Any suggestions?

var (
            orderBy string
            count   uint
            where   = map[string]interface{}{}
            data    []ActorsWithFilms
            db      = ms.db.Table("actor")
        )

        if filter.ActorName != "" {
            where["actor_name"] = filter.ActorName
        }

        if filter.UpdatedFrom != "" {
            db = db.Where("actor.updated_at >= ?", filter.UpdatedFrom)
        }

        if len(filter.FilmNames) != 0 {
            db = db.Where("film.name in (?)", filter.FilmNames)
        }

        if len(filter.Statuses) != 0 {
            db = db.Where("actor.status in (?)", filter.Statuses)
        }

        err := db.
            Joins("join film on film.actorID = actor.id").
            Where(where).
            Preload("Film").
            Order(orderBy).
            Limit(filter.GetLimit()).
            Offset(filter.Offset).
            Find(&data).
            Count(&count).
            Error
  • 写回答

1条回答 默认 最新

  • douhandie6615 2019-05-03 12:26
    关注

    This actually doesn't look bad to me. Gorm exposes a method chaining interface exactly so you can do query building like this, so I wouldn't say this is a code smell at all.

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试