简体   繁体   中英

Sequelize order by join table

I have a Duel type, each Duel has a list of players. 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. I have tried different combinations of order value, but nothing worked. 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. 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. In your example you are aliasing User as players and DuelPokemon as duelPokemons . Note that you will have needed to define these associations for each Model . Your question mentions duel_players which doesn't exist in your example, but I think you meant to say 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']],
});

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