How to use the literal function from sequelize

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

161
162
163
164
165
166
167
168
169
170
	{
		first_name,
		last_name,
		phone,
		// password: hashedPassword,
		updatedAt: Sequelize.literal('CURRENT_TIMESTAMP'),
	},
	{ returning: true, where: { id_user: id } }
);
// Hàm update trả về một mảng có một phần tử, là số lượng bản ghi đã được cập nhật.
fork icon0
star icon1
watch icon1

+ 14 other calls in file

720
721
722
723
724
725
726
727
728
if (position1 >= 0 || position2 >= 0) { image = ''}

const activeMessage = await Message.findOne({
  where: {
    startAt: { [Sequelize.Op.lt]: Sequelize.literal('CURRENT_TIMESTAMP()') },
    endAt: { [Sequelize.Op.gt]: Sequelize.literal('CURRENT_TIMESTAMP()') },
    eventId: event.id
  }
});
fork icon0
star icon1
watch icon4

40
41
42
43
44
45
46
47
48
49
// to get the associated row count of each author
// https://sequelize.org/docs/v6/other-topics/sub-queries/#using-sub-queries-for-complex-ordering
attributes: {
  include: [
    [
      Sequelize.literal(`(
        SELECT COUNT(*)
        FROM books AS book
        WHERE
        book.author_id = author.id
fork icon0
star icon1
watch icon1

-1
fork icon114
star icon0
watch icon39

+ 19 other calls in file

172
173
174
175
176
177
178
179
180
181
case 'link_added':
case 'link_removed':
    return this.__StateEvents.create({
        type: type,
        linkId: params.linkId,
        timestamp: Sequelize.literal('CURRENT_TIMESTAMP')
    }).then(e => this.getStateEvent(e.id));
case 'node_added':
case 'node_removed':
case 'node_updated':
fork icon4
star icon42
watch icon5

+ 3 other calls in file

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

187
188
189
190
191
192
193
194
195
196
}

function getUpdateSeedersTorrents(limit = 100) {
  const until = moment().subtract(7, 'days').format('YYYY-MM-DD');
  return Torrent.findAll({
    where: literal(`torrent."updatedAt" < \'${until}\'`),
    limit: limit,
    order: [
      ['seeders', 'DESC'],
      ['updatedAt', 'ASC']
fork icon24
star icon0
watch icon0

+ 3 other calls in file

1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
userId = req.session?.user?.id || req.get('SSL_CLIENT_S_DN_CN');

const user_id = getUserIdFromSAMLUserId(req);

await this.gcUser.update(
	{ api_requests: Sequelize.literal('api_requests - 1') },
	{ where: { user_id: user_id } }
);

res.status(200).send();
fork icon7
star icon11
watch icon12

+ 4 other calls in file

26
27
28
29
30
31
32
33
34
35
// Post a new game to the games table.
router.post("/", validateToken, async (req, res) => {
	if(req.body.mode === "classic") {
		await Daily.update(
			{
				numPlayed: sequelize.literal('numPlayed + 1'), 
				numWins: (req.body.win) ? sequelize.literal('numWins + 1') : sequelize.literal('numWins'), 
				numLosses: (req.body.win) ? sequelize.literal('numLosses') : sequelize.literal('numLosses + 1'), 
				num1Guess: (req.body.win && req.body.numGuesses === 1) ? sequelize.literal('num1Guess + 1') : sequelize.literal('num1Guess'), 
				num2Guess: (req.body.win && req.body.numGuesses === 2) ? sequelize.literal('num2Guess + 1') : sequelize.literal('num2Guess'), 
fork icon0
star icon2
watch icon1

+ 19 other calls in file

79
80
81
82
83
84
85
86
87
88
const matricula = req.params.matricula || req.body.matricula;
const { id_student } = req;
const gradeTest = await Test.findOne({
  where: {
    id_grade: {
      [Op.eq]: literal(
        `(SELECT id_grade FROM grades WHERE id_course = ${id_course} AND id_student ='${id_student}')`
      ),
    },
  },
fork icon0
star icon2
watch icon2

253
254
255
256
257
258
259
260
261
262
'description',
'price',
'createdAt',
'updatedAt',
[
    Sequelize.literal(
        `(SELECT ROUND(AVG(stars), 1) FROM ${schema ? `"${schema}"."Reviews"` : 'Reviews'
        } WHERE "Reviews"."spotId" = "Spot"."id")`
    ),
    'avgRating',
fork icon0
star icon2
watch icon1

+ 9 other calls in file

16
17
18
19
20
21
22
23
24
25
  allowNull: false,
},
createdAt: {
  type: Sequelize.DATE,
  allowNull: false,
  defaultValue: Sequelize.literal('NOW()'),
},
updatedAt: {
  type: Sequelize.DATE,
  allowNull: false,
fork icon0
star icon1
watch icon0

921
922
923
924
925
926
927
928
929
930
supportArticle(req, res) {
  api
    .updateData(
      "ArticleContent",
      {
        likesNum: Sequelize.literal("likesNum+1"),
      },
      { id: req.query.id }
    )
    .then((result) => {
fork icon0
star icon0
watch icon1

370
371
372
373
374
375
376
377
378
379
  popularSkills = await models.popular_skills
    .findAll({
      attributes: ["name"],
      limit: 5,
      raw: true,
      order: Sequelize.literal("count DESC"),
    })
    .map((skill) => skill["name"]);
} catch (err) {
  console.log("popular_skills query failed", err);
fork icon0
star icon0
watch icon1

+ 5 other calls in file

384
385
386
387
388
389
390
391
392
393
const inbox = await this.PlayerServerMessage.findOne(
  {
    attributes: {
      include: [
        [
          sequelize.literal(`(
            SELECT Count(*)
            FROM PeerMessages as pm
            WHERE 
              pm.receiverId = PlayerServerMessage.PlayerId 
fork icon0
star icon0
watch icon2

+ 39 other calls in file

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
  });
  return res;
}
else if (key === 'content_types' && value) {
  let contentTypes = _.map(data.request.filters[key], (val) => {
    return Sequelize.literal(`'${val}' = ANY (\"program\".\"content_types\")`);
  });

  let targetprimarycategorynames = _.map(data.request.filters[key], (val) => {
    return Sequelize.literal(`'${val}' = ANY (\"program\".\"targetprimarycategorynames\")`);
fork icon0
star icon0
watch icon1

+ 4 other calls in file

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
const promises = [];
delete data.request.filters.nomination;

_.forEach(roles, (role) => {
  let whereCond = {
    $contains: Sequelize.literal(`cast(nomination.rolemapping->>'${role}' as text) like ('%${user_id}%')`),
  };
  promises.push(
    model.nomination.findAndCountAll({
      where: {
fork icon0
star icon0
watch icon1

5379
5380
5381
5382
5383
5384
5385
5386
5387
5388

var randumProductArray = [];

if(storeId && storeId !='')	{
	
	var randumProductList = await models.products.findAll({attributes: ['id','sku','title','slug','shortDescription','price','specialPrice','weight','size'], where: { status:'active', storeId:storeId, bestSellers: { $ne: 'yes' }}, order: Sequelize.literal('rand()'), limit: 3 });

	if(randumProductList.length>0){

		////////////////////////// catelog price rule start /////////////////////////////////////
fork icon0
star icon0
watch icon1

+ 2 other calls in file

145
146
147
148
149
150
151
152
153
154
    "latitude",
    "longitude",
    [Sequelize.literal(haversine), 'distance']
],
order: Sequelize.col('distance'),
having: Sequelize.literal(`distance <= ${distance}`),
include: [
    {
        model: db.product_reviews,
        required: false,
fork icon0
star icon0
watch icon1

+ 74 other calls in file

344
345
346
347
348
349
350
351
352
353
nest: true,
attributes: {
  // "*",
  include: [
  //   [
  //   Sequelize.literal(
  //     `(SELECT SUM(targets.target) FROM needs_analyses LEFT JOIN targets on needs_analyses.allocation = targets.staff_id WHERE MONTH(date) = ${_month} AND YEAR(date) = ${_year}  )`
  //   ),
  //   "total_targets",
  // ],
fork icon0
star icon0
watch icon1

+ 223 other calls in file