我有一个模型,比如说Base,它具有一个Details1模型或一个Details2模型,具体取决于字段“类型”的值(表示“ Details1”或“ Details2”)。
Details1
和Details2
都有一个字段“ orderField”。
是否有一种方法可以根据Base.type = details1或details2来通过Details1.orderField或Details2.orderField对Base模型的行进行排序?
我尝试查找与订购有关的sequelize
文档:http://docs.sequelizejs.com/manual/querying.html#ordering
我已经尝试过了:
Base.findAll(
{
include: [
{ model: Details1 },
{ model: Details2 }
],
order: [
[
{ model: Details1, as: 'Details1' }, 'orderField', 'DESC'
],[
{ model: Details2, as: 'Details2' }, 'orderField', 'DESC'
]
]
});
但是,以上代码分别按Details1.orderField和Details2.orderField排序基本模型的行。
例如,如果我有以下数据:
{type: details1, Details1: {orderField: 2}}
{type: details2, Details2: {orderField: 1}}
{type: details2, Details2: {orderField: 5}}
{type: details1, Details1: {orderField: 4}}
{type: details2, Details2: {orderField: 3}}
则预期顺序为:
{type: details2, Details2: {orderField: 5}}
{type: details1, Details1: {orderField: 4}}
{type: details2, Details2: {orderField: 3}}
{type: details1, Details1: {orderField: 2}}
{type: details2, Details2: {orderField: 1}}
但是,我得到的输出为:
{type: details1, Details1: {orderField: 4}}
{type: details1, Details1: {orderField: 2}}
{type: details2, Details2: {orderField: 5}}
{type: details2, Details2: {orderField: 3}}
{type: details2, Details2: {orderField: 1}}
答案 0 :(得分:0)
您可以尝试做的一件事:使用CASE语句派生单个字段进行排序。
order: [
[Sequelize.literal("case when details1.orderField not null then details1.orderField else details2.orderField end")]
]
您可能必须摆弄表别名才能使其正常工作。