How to use the col function from sequelize

Find comprehensive JavaScript sequelize.col code examples handpicked from public code repositorys.

sequelize.col is a method in Sequelize that allows you to specify a database column as an expression.

69
70
71
72
73
74
75
76
77
78
let count

try {
  const wordbookModel = await new WordbookModel()
  const findOptions = {
    attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'num']]
  }

  if (typeof historyId === 'number') {
    findOptions.where = {
fork icon11
star icon108
watch icon4

+ 9 other calls in file

57
58
59
60
61
62
63
64
65
66
indexes: [
  {
    unique: true,
    name: 'files_unique_file_constraint',
    fields: [
      col('infoHash'),
      fn('COALESCE', (col('fileIndex')), -1),
      fn('COALESCE', (col('imdbId')), 'null'),
      fn('COALESCE', (col('imdbSeason')), -1),
      fn('COALESCE', (col('imdbEpisode')), -1),
fork icon24
star icon0
watch icon0

+ 5 other calls in file

How does sequelize.col work?

sequelize.col is a method in the Sequelize ORM library for Node.js that creates an SQL column expression to reference a specific table column within a query. It takes a string argument that represents the name of the column and returns a column expression object. This column expression can be used in queries to perform operations or filtering based on the specified column.

379
380
381
382
383
384
385
386
387
388
		upload_date: {
			[Op.gt]: yearAgo,
		},
	},
	attributes: [
		[Sequelize.fn('date_trunc', 'month', Sequelize.col('upload_date')), 'month'],
		[Sequelize.fn('count', '*'), 'count'],
	],
	group: 'month',
});
fork icon7
star icon11
watch icon12

+ 9 other calls in file

1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
const { clone_name } = req.body;

const user_id = getUserIdFromSAMLUserId(req);

let ids = await this.gcHistory.findAll({
	attributes: [[Sequelize.fn('MAX', Sequelize.col('id')), 'id']],
	where: {
		clone_name,
		had_error: 'f',
		user_id: user_id,
fork icon7
star icon11
watch icon12

+ 4 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { Sequelize, Model, DataTypes } = require("sequelize");
const sequelize = new Sequelize("sqlite::memory:");

class User extends Model {}
User.init(
  {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
  },
  { sequelize, modelName: "user" }
);

const users = await User.findAll({
  attributes: ["id", "firstName", [sequelize.col("lastName"), "surname"]],
});

Here we're using sequelize.col('lastName') to create a reference to the lastName column in the user table, and we're giving it the alias surname using the array syntax. This will result in a query that looks something like this: sql Copy code

17
18
19
20
21
22
23
24
25
26
where: {
  UserId: query.userId,
  EventId: query.eventId,
},
attributes: [
  [Sequelize.fn('ST_AsGeoJSON', Sequelize.col('shape')), 'shape'],
  'distance',
  'area',
  'id',
  'startTime',
fork icon4
star icon0
watch icon1

+ 5 other calls in file

18
19
20
21
22
23
24
25
26
27
  {model: models.Users}
],
attributes: {
  include: [[
    sequelize.fn('ST_DWithin',
    sequelize.col('geolocation'),
    sequelize.literal(`ST_Point(${req.body.latitude}, ${req.body.longitude})::geography`),
    1000), 'nearby'
  ]]
}
fork icon2
star icon4
watch icon4

99
100
101
102
103
104
105
106
107
108
109
        callback(err);
    });
}


exports.countAll = function(callback) {
    Item.findAll({ attributes: [[Sequelize.fn('COUNT', Sequelize.col('id')), 'no_items']] } ).then(function(n) {
        callback(null, n[0].get('no_items'));
    }).error(function(err) {
        callback(err);
    });
fork icon3
star icon0
watch icon1

+ 2 other calls in file

69
70
71
72
73
74
75
76
77
78
  "jumlah",
],
[
  sequelize.fn(
    "sum",
    sequelize.col("prodtrans.total_purchased_price")
  ),
  "total_biaya",
],
[
fork icon2
star icon0
watch icon0

+ 4 other calls in file

232
233
234
235
236
237
238
239
240
//         },
//         { model: Review,
//             attributes: []
//         }]
// query.attributes = {
//     include: [[Sequelize.fn("AVG", Sequelize.col("Reviews.stars")), 'avgRating']]
// }

// query.group = ['Spot.id', 'SpotImages.id', "Reviews.spotId"]
fork icon0
star icon2
watch icon1

+ 24 other calls in file

106
107
108
109
110
111
112
113
114
115
}

const locations = await event.getLocations()
const tablesGroupedCount = await Table.findAll(
  {
    attributes: ['LocationId', 'EventId', [Sequelize.fn('count', Sequelize.col('LocationId')), 'count']],
    group: ['LocationId', 'EventId'],
    having: { 'EventId': event.get('id') }
  }
)
fork icon0
star icon1
watch icon4

+ 11 other calls in file

707
708
709
710
711
712
713
714
715
716
//unread message count
router.get('/unread_messages', (req, res, next) => {
  console.log(req.query.userId)
  MessageRecord.findAll({
    where: { TMESSAGES_Record_UID: req.query.userId, TMESSAGES_Record_Read_Status: "Sent", TMESSAGES_Record_IS_Delete: false },
    attributes: ["TMESSAGES_Record_Chat_Room_ID", [Sequelize.fn('count', Sequelize.col('TMESSAGES_Record_Chat_Room_ID')), 'Unread_msg_count']],
    group: ['TMESSAGES_Record_Chat_Room_ID'],
  })
    .then(unreadMsgCount => {
      console.log(unreadMsgCount)
fork icon0
star icon1
watch icon1

+ 3 other calls in file

95
96
97
98
99
100
101
102
103
104
}
}
],
attributes: {
  include: [
    [Sequelize.fn('SUM', Sequelize.col('orders.OrderProducts.quantity')), 'soldProductCount']
  ],
  separate: true
},
group: ['orders.OrderProducts.productId'],
fork icon9
star icon0
watch icon0

124
125
126
127
128
129
130
131
132
133
    }

const order = sort.length
  ? sort.reduce((items, s) => {
      const customField = allFields.find(({ dest }) => dest === s.name)
      return [...items, [customField ? sequelize.col(customField.source) : s.name, s.order || 'ASC']]
    }, [])
  : undefined

if (filters.length && filterItems.length) filters[0].items = [...filters[0].items, ...filterItems]
fork icon0
star icon0
watch icon1

+ 2 other calls in file

54
55
56
57
58
59
60
61
62
63
contractId: [sequelize.col('contract.id'), 'contractId'],
patientCpfCnpj: [sequelize.col('contract.customer.patientAdherer.cpfCnpj'), 'patientCpfCnpj'],
patientName: [sequelize.col('contract.customer.patientAdherer.name'), 'patientName'],
paymentMethodDescription: [sequelize.col('paymentMethod.description'), 'paymentMethodDescription'],
paymentMethodNumberInstallments: [
  sequelize.col('paymentMethod.numberInstallments'),
  'paymentMethodNumberInstallments',
],
paymentMethodFine: [sequelize.col('paymentMethod.fine'), 'paymentMethodFine'],
paymentMethodInterest: [sequelize.col('paymentMethod.interest'), 'paymentMethodInterest'],
fork icon0
star icon0
watch icon1

+ 2 other calls in file

244
245
246
247
248
249
250
251
252
// Find average of stars and set avgStarRating property
const reviewAvg = await Review.findAll({
  where: {
    spotId
  },
  attributes: [[Sequelize.fn('AVG', Sequelize.col('stars')), 'avg_rating']]
})

formatSpot.avgStarRating = reviewAvg[0].dataValues.avg_rating;
fork icon0
star icon0
watch icon1

113
114
115
116
117
118
119
120
121
122
attributes: [
  'sbi',
  'crn',
  'customer_name',
  'business_name',
  [fn('LOWER', col('business_email')), 'businessEmail'],
  'business_address',
  'last_updated_at',
  'waiting_updated_at',
  'access_granted'
fork icon0
star icon0
watch icon5

+ 11 other calls in file

301
302
303
304
305
306
307
308
309
310
  throw new  AppError('No groupe found with that Id', 404);
}
// const nombreSeance = await groupe.getPresences({
//   attributes: [
//     "datePresence",
//    [sequelize.fn("COUNT", sequelize.col("presence.id")), "count_players"],  
//   ],
//   include:[{model:Student , left:true},
//   {model:Groupe , left:true}
//   ],
fork icon0
star icon0
watch icon0

+ 26 other calls in file

45
46
47
48
49
50
51
52
53
54
namesConcated: sequelize.where(
  sequelize.fn(
    "concat",
    sequelize.col("firstName"),
    " ",
    sequelize.col("lastName")
  ),
  {
    [sequelize.Op.iLike]: `%${req.query.term}%`,
  }
fork icon0
star icon0
watch icon1

+ 9 other calls in file

1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
}
///////////////////////////////////// brand is checked end ///////////////////

///////////////////////////////////// option value is checked start ///////////////////
if(option_value !='' && option_value != null){
	// var optionTitle = await models.products.findAll({attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('optionTitle')), 'optionTitle']], where : { optionTitle: !null, storeId : storeId, status : 'active' }})
	var optionTitle = await sequelize.query("SELECT DISTINCT optionTitle FROM products where optionTitle is not null and optionTitle != '' and storeId = "+storeId+"",{ type: Sequelize.QueryTypes.SELECT });
	if (optionTitle.length > 0) {
		var multiOptionValue = ''
		var option_value_arr = req.body.data.option_value.split(",");
fork icon0
star icon0
watch icon1

+ 2 other calls in file

52
53
54
55
56
57
58
59
60
61
  vendas.forEach((venda) => {
    venda.data = moment(venda.data).format('DD/MM/YYYY');
  });
      //////////////////////Quantidade
var amountQ = await Venda.findOne({
  attributes: [sequelize.fn("sum", sequelize.col("quantidade"))],
  
  raw: true
});
var quantidade = (Number(amountQ['sum(`quantidade`)']))
fork icon0
star icon0
watch icon1

+ 2 other calls in file