简体   繁体   中英

How to pass a seed value to random order function in Sequelize

In SQL dialects you can sort by random and you can pass a seed to the random function in order to get a repeatable random order of rows.

In MySQL you'd do it like this:

SELECT * FROM `users` ORDER BY RAND("192.168.1.1")

I'm aware of how to use the RAND function when querying with Sequelize:

users.findAll({
  order: [sequelize.random()],
});

I can't seem to figure out how to pass a seed to the random function.

I've looked at the docs: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-random

And it looks like the sequelize.random() function doesn't take any parameters.

Is this possible?

If you wish your query will work only in MySQL then just use sequelize.fn :

users.findAll({
  order: [sequelize.fn('RAND', '192.168.1.1')],
});

Absent any official documentation mention of the issue, the definition of the sequelize.random() method in sequelize.js (line 892) shows that it doesn't accept any parameters currently, and simply functions as a method by which to properly build a query dependent on the specific RDBMS configured for use.

As such, it is safe to say that, as of this writing, this is currently not supported in sequelize 's master branch by default; @Anatoly's answer shows how you might be able to achieve this by leveraging sequelize.fn in your own project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM