属性

想要只选择某些属性,可以使用 attributes 选项. 通常是传递一个数组:

  1. Model.findAll({
  2. attributes: ['foo', 'bar']
  3. });
  1. SELECT foo, bar ...

属性可以使用嵌套数组来重命名:

  1. Model.findAll({
  2. attributes: ['foo', ['bar', 'baz']]
  3. });
  1. SELECT foo, bar AS baz ...

也可以使用 sequelize.fn 来进行聚合:

  1. Model.findAll({
  2. attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
  3. });
  1. SELECT COUNT(hats) AS no_hats ...

使用聚合功能时,必须给它一个别名,以便能够从模型中访问它. 在上面的例子中,你可以使用 instance.get('no_hats') 获得帽子数量.

有时,如果你只想添加聚合,则列出模型的所有属性可能令人厌烦:

  1. // This is a tiresome way of getting the number of hats...
  2. Model.findAll({
  3. attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
  4. });
  5. // This is shorter, and less error prone because it still works if you add / remove attributes
  6. Model.findAll({
  7. attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }
  8. });
  1. SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...

同样,它也可以排除一些指定的表字段:

  1. Model.findAll({
  2. attributes: { exclude: ['baz'] }
  3. });
  1. SELECT id, foo, bar, quz ...