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

ぃ、小莉子 提交于 2020-12-15 03:43:45

问题


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?


回答1:


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')],
});



回答2:


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.



来源:https://stackoverflow.com/questions/65187842/how-to-pass-a-seed-value-to-random-order-function-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!