Sequelize OR BY BY

问题描述 投票:0回答:1

您好,我想查询公司并列出按名称排序的所有用户这就是我所拥有的。关系很好,只是排序不起作用。调试生成的查询时,我看不到ORDER BY名称。

const user = {
    model: models.User,
    as: "Users",
    order: [["name", "asc"]]
};

const options = {
    where: { id: 1 },
    include: [user]
};

models.Company.findOne(options)
    .then(company => console.log(company))
    .catch(error => console.log(error.message));
node.js sequelize.js
1个回答
2
投票

从接口定义文件中,我们可以看到IncludeOptions.order选项的注释。

  /**
   * Order include. Only available when setting `separate` to true.
   */
  order?: Order;

因此,您需要将separate设置为true。我假设CompanyUser之间的关系是一对多。

"sequelize": "^5.21.3"。例如:

import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';

class Company extends Model {}
Company.init({}, { sequelize, modelName: 'companies' });

class User extends Model {}
User.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'users' },
);

Company.hasMany(User, { as: 'Users' });

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // seed
    await Company.create(
      { Users: [{ name: 'tim' }, { name: 'elsa' }, { name: 'james' }] },
      { include: [{ model: User, as: 'Users' }] },
    );
    // test
    const company = await Company.findOne({
      where: { id: 1 },
      include: [
        {
          model: User,
          as: 'Users',
          separate: true,
          order: [['name', 'asc']],
        },
      ],
    });
    console.log(company.Users);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

执行结果和生成的SQL:

Executing (default): SELECT "companies"."id" FROM "companies" AS "companies" WHERE "companies"."id" = 1;
Executing (default): SELECT "id", "name", "companyId" FROM "users" AS "users" WHERE "users"."companyId" IN (1) ORDER BY "users"."name" ASC;
[ users {
    dataValues: { id: 2, name: 'elsa', companyId: 1 },
    _previousDataValues: { id: 2, name: 'elsa', companyId: 1 },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       include: undefined,
       includeNames: undefined,
       includeMap: undefined,
       includeValidated: true,
       raw: true,
       attributes: undefined },
    isNewRecord: false },
  users {
    dataValues: { id: 3, name: 'james', companyId: 1 },
    _previousDataValues: { id: 3, name: 'james', companyId: 1 },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       include: undefined,
       includeNames: undefined,
       includeMap: undefined,
       includeValidated: true,
       raw: true,
       attributes: undefined },
    isNewRecord: false },
  users {
    dataValues: { id: 1, name: 'tim', companyId: 1 },
    _previousDataValues: { id: 1, name: 'tim', companyId: 1 },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       include: undefined,
       includeNames: undefined,
       includeMap: undefined,
       includeValidated: true,
       raw: true,
       attributes: undefined },
    isNewRecord: false } ]

数据库中的数据记录:

node-sequelize-examples=# select * from "users";
 id | name  | companyId
----+-------+-----------
  1 | tim   |         1
  2 | elsa  |         1
  3 | james |         1
(3 rows)

node-sequelize-examples=# select * from "companies";
 id
----
  1
(1 row)
热门问题
推荐问题
最新问题