Home > database >  How to Customize GROUP_CONCAT Separator in Sequelize?
How to Customize GROUP_CONCAT Separator in Sequelize?

Time:01-06

Assuming I have this seqeulize code bellow

groupAccess.findAll({
  attributes: [
    'id',
    'group_name',
    'description',
    [sequelize.fn('GROUP_CONCAT', sequelize.col('module_name')), 'module_name']
  ],
  group: ['group_name']
})

The result of it's query will be like

id  |  group_name  |  description  |  module_name
---- -------------- --------------- ---------------------------
1   |  A           |  desc A       |  mod_1,mod_2,mod_3
4   |  B           |  desc B       |  mod_4,mod_5,mod_6,mod_7
8   |  C           |  desc C       |  mod_8,mod_9,mod_10
11  |  D           |  desc D       |  mod_11,mod_12

and sequelize.js res will be like:

[
  {
    id: "1",
    group_name: "A",
    description: "desc A",
    module_name: "mod_1,mod_2,mod_3"
  },
  {
    id: "4",
    group_name: "B",
    description: "desc B",
    module_name: "mod_4,mod_5,mod_6,mod_7"
  },
  {
    id: "8",
    group_name: "C",
    description: "desc C",
    module_name: "mod_8,mod_9,mod_10"
  },
  {
    id: "11",
    group_name: "D",
    description: "desc D",
    module_name: "mod_11,mod_12"
  },
]

Problem: How to change the commas (separators) to another symbol as the separator (in e.g: dash-arrow -> symbol as the separator) IN SEQUELIZE?

Expected query:

id  |  group_name  |  description  |  module_name
---- -------------- --------------- ---------------------------
1   |  A           |  desc A       |  mod_1->mod_2->mod_3
4   |  B           |  desc B       |  mod_4->mod_5->mod_6->mod_7
8   |  C           |  desc C       |  mod_8->mod_9->mod_10
11  |  D           |  desc D       |  mod_11->mod_12

Expected res of sequelize.js:

[
  {
    id: "1",
    group_name: "A",
    description: "desc A",
    module_name: "mod_1->mod_2->mod_3"
  },
  {
    id: "4",
    group_name: "B",
    description: "desc B",
    module_name: "mod_4->mod_5->mod_6->mod_7"
  },
  {
    id: "8",
    group_name: "C",
    description: "desc C",
    module_name: "mod_8->mod_9->mod_10"
  },
  {
    id: "11",
    group_name: "D",
    description: "desc D",
    module_name: "mod_11->mod_12"
  },
]

CodePudding user response:

Found this on GitHub (https://github.com/sequelize/sequelize/issues/3390#issuecomment-84649641); not 100% sure if this works (since I'm not familiar with sequelize), but you can try:

groupAccess.findAll({
  attributes: [
    'id',
    'group_name',
    'description',
    [sequelize.fn('GROUP_CONCAT', sequelize.literal(`module_name SEPARATOR '->'`)), 'module_name']
  ],
  group: ['group_name']
})
  • Related