简体   繁体   English

按连接表顺序排列

[英]Sequelize order by join table

I have a Duel type, each Duel has a list of players.我有一个Duel类型,每个Duel都有一个玩家列表。 This is my query and relationship:这是我的查询和关系:

const duel = Duel.findByPk(id, {
    include: duelRelations,
  });


const duelRelations = [{
  model: User,
  as: 'players',
  include: [{
    model: DuelPokemon,
    required: false,
    as: 'duelPokemons',
  }],
}, {
  model: DuelActionLog,
  required: false,
  as: 'logs',
}];

relationship:关系:

// Each duel has many users
Duel.hasMany(User, {
  foreignKey: 'duel_id',
  as: 'players',
});

I want to get the players array sorted by the createdAt field of the duel_players table.我想要得到的players阵列通过排序createdAt的领域duel_players表。 I have tried different combinations of order value, but nothing worked.我尝试了order值的不同组合,但没有任何效果。 No idea how to define it.不知道怎么定义。

Any idea?任何的想法?

Thanks谢谢

You should use sequelize.col() to specify the column from the joined table that you want to sort by in the order property of the findByPk options.您应该使用sequelize.col()findByPk选项的order属性中指定要作为排序依据的连接表中的列。 Each order by entry is an array with two parts (the column, then the order) an you can pass in multiple entries to sort by multiple columns.每个按条目排序是一个包含两部分(列,然后是顺序)的数组,您可以传入多个条目以按多列排序。

I moved the duelRelations into the options to make it easier to read.我将duelRelations移到选项中以使其更易于阅读。 In your example you are aliasing User as players and DuelPokemon as duelPokemons .在您的示例中,您将User别名为playersDuelPokemonduelPokemons Note that you will have needed to define these associations for each Model .请注意,您需要为每个Model定义这些关联。 Your question mentions duel_players which doesn't exist in your example, but I think you meant to say players.createdAt .您的问题提到了在您的示例中不存在的duel_players ,但我认为您的意思是说players.createdAt

const duel = Duel.findByPk(id, {
  include: [
    {
      model: User,
      as: 'players',
      include: { // can be an object to include single table
        model: DuelPokemon,
        required: false,
        as: 'duelPokemons',
      },
    },
    {
      model: DuelActionLog,
      required: false,
      as: 'logs',
    },
  ],
  order: [[sequelize.col('players.createdAt', 'DESC']],
});

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

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