简体   繁体   English

在 Postgres 上使用 Knex.js 在 Boolean 列上排序

[英]Orderby on Boolean column with Knex.js on Postgres

How can I use knex.js's orderBy method on a boolean column for a postgres database?如何在 postgres 数据库的 boolean 列上使用 knex.js 的 orderBy 方法? Using "asc" or "desc" in the object taken by orderby doesn't work (rows with true or false appear after each other).在 orderby 获取的 object 中使用“asc”或“desc”不起作用(具有 true 或 false 的行一个接一个出现)。

Here is some sample code (assuming its wrapped in an async function and the enabled column is a boolean):这是一些示例代码(假设它包含在异步 function 中,并且启用的列是布尔值):

const users = await knex("person").orderBy("enabled", "desc");

Is there a knex method that is better suited for this or should I run a raw query within knex's orderByRaw method?是否有更适合此的 knex 方法,或者我应该在 knex 的 orderByRaw 方法中运行原始查询? What would the raw SQL query be?原始的 SQL 查询是什么? I don't need to worry about null fields at the moment either but there are rows where the enabled column is null as it is neither true or false.我现在也不需要担心 null 字段,但是有些行启用的列是 null 因为它既不是真也不是假。

Sorry, this line of code is actually working.抱歉,这行代码确实有效。 In my project that I can't share, I was doing an orderBy with an array of sorts that default to "asc".在我无法分享的项目中,我正在使用默认为“asc”的排序数组执行 orderBy。 When I removed all the sorts except for the boolean sort, it worked where "desc" had true show first and "asc" had false show first.当我删除除 boolean 排序之外的所有排序时,它在“desc”首先显示真实而“asc”首先显示错误的情况下工作。 I don't know how knex and/or postgres handles the orderBy array and which sorts have higher priority but I should have fixed the default issue beforehand.我不知道 knex 和/或 postgres 如何处理 orderBy 数组以及哪些排序具有更高的优先级,但我应该事先修复默认问题。

I'll leave this question and answer here incase other people have this issue and maybe also have a similar situation with using an array of sorts.我将在此处留下这个问题并回答,以防其他人遇到此问题,并且可能在使用各种数组时也有类似的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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