【问题标题】:how can concat columns in sequelize?续集中如何连接列?
【发布时间】:2020-11-11 01:14:03
【问题描述】:

我正在使用 sequelize 和 node.js。我想将 PrimaryPractice 模型的列的值相互连接。 我怎么解决这个问题? 这是我的代码:

ProviderPayer.findAll({
                  where: {
                      orgPayerId: {
                          [Op.in]: orgPayerIds
                      }
                  },
                  attributes: ["effective_date"],
                  include: [{
                          model: PayerTracks,
                          attributes: ["title"],
                          as: "payers",
                      },
                      {
                          model: User,
                          where: {
                              id: {[Op.in]: userIds},
                              deletedAt: null,
                              status: {[Op.ne]: STATUS.INACTIVE}
                          },
                          attributes: ["id"],
                          include: [
                              {
                                  model: PrimaryPractice,
                                  as: "primaryPractice",
                                  attributes: [
                                   "addressStreetPrimPract", 
                                   "addressStreet2PrimPract", 
                                   "addressCityPrimPract", 
                                   "addressStatePrimPract", 
                                   "addressZipPrimPract"]
                              }
                          ]
                      }

                  ]
              })

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    如果您的 DBMS 具有类似 CONCAT 的功能,那么您可以尝试以下操作:

    attributes: [
      [
        sequelize.fn('CONCAT',
          sequelize.col('addressStreetPrimPract'), ', ', 
          sequelize.col('addressStreet2PrimPract'), ', ', 
          sequelize.col('addressCityPrimPract'), ', ', 
          sequelize.col('addressStatePrimPract'), ', ', 
          sequelize.col('addressZipPrimPract')
        ),
        'concatenated_fields_alias'
      ],
    ],
    

    【讨论】:

    • 我删除了旧属性,只保留了 CONCAT
    【解决方案2】:
    attributes: [sequelize.fn('CONCAT',
        sequelize.col('addressStreetPrimPract'), ' ',
        sequelize.col('addressStreet2PrimPract'), ' ',
        sequelize.col('addressCityPrimPract'), ' ',
        sequelize.col('addressStatePrimPract'), ' ',
        sequelize.col('addressZipPrimPract')
    ),
    'name_of_concatenated_fields'
    ]
    

    您也可以看到这个 SO answer 以供参考

    【讨论】:

    • 我运行此代码但返回此错误消息:“在急切加载期间,尝试使用 Sequelize.cast 或 Sequelize.fn 选择属性而不为结果指定别名。这意味着该属性不会添加到返回的实例”
    • 我在fn之前忘记使用sequelize了,现在试试
    • 这是真的,要么我们必须再放一个[]
    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2017-10-12
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多