node.js - Sequelize : 'findAll' in instance method getParticipants()?

标签 node.js sequelize.js models instance-methods

我的 session 实例方法的规范:

getParticipants() : Promise -> Participant array



session 模型:
return sequelize.define('conference', {

    id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true
    },

    name: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true
    },

    maxParticipants: {
        type: Sequelize.INTEGER,
        allowNull: false
    },

    fileShareSession: {
        type: Sequelize.STRING,
        defaultValue: null,
        allowNull: true
    },

    startDate: {
        type: Sequelize.DATE,
        defaultValue: null,
        allowNull: true
    },

    endDate: {
        type: Sequelize.DATE,
        defaultValue: null,
        allowNull: true
    },

    state: {
        type: Sequelize.ENUM(
            ConferenceState.new,
            ConferenceState.starting,
            ..
        ),
        defaultValue: ConferenceState.new,
        required: true,
        allowNull: false
    }

参与者模型:
return sequelize.define('participant', {

    id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true
    },

    displayName: {
        type: Sequelize.STRING,
        defaultValue: null,
        allowNull: true
    },

    mediaResourceId: {
        type: Sequelize.STRING,
        defaultValue: null,
        allowNull: true
    },

    screenSharingId: {
        type: Sequelize.STRING,
        defaultValue: null,
        allowNull: true
    },

    mediaType: {
        type: Sequelize.ENUM(
            MediaType.AUDIO_VIDEO),
        defaultValue: MediaType.AUDIO_VIDEO,
        allowNull: false
    },

    state: {
        type: Sequelize.ENUM(
            ParticipantState.new,
            ParticipantState.joining,
            ..
        ),
        defaultValue: ParticipantState.new,
        required: true,
        allowNull: false
    }

问题:

那么我是否可以在我的 session 实例模型中执行参与者.findAll?如果是,我是否可以通过 findAll 返回一个数组?

我会这样做:
// getParticipants() : Promise -> Participant array
      getParticipants() {
          return new Promise((resolve, reject) => {
              var Participant = sequelize.models.participant;
              Participant.findAll({
                  where: {
                      id: id
                  }
              }).then(function(participant) {
                  if (_.isObject(participant)) {
                      resolve(participant);
                  } else {
                      throw new ResourceNotFound(conference.name, {id: id});
                  }
              }).catch(function(err) {
                  reject(err);
              });
          });
      },

最佳答案

当你在表之间建立关系时,延迟加载是通过 sequelize 实现的。您可以建立如下关系:

var Conference = sequelize.define('conference', { ... });

var Participant = sequelize.define('participant', { ... });

Conference.belongsToMany(Participant, { through: 'ConferenceParticipants'});

Participant.belongsToMany(Conference, { through: 'ConferenceParticipants'});

然后,您可以在查询数据库时实现 EAGER 加载,例如:
// Obtain the participant list included in the original object (EAGER)
var conference = 
 Conference.findOne({ 
    attributes: ['field1', 'field2', ...],
    where: {title: 'Conference A'},
    includes: [{
      attributes: ['field1', 'field2', ...],
      model: Participant,
      through: { model: 'ConferenceParticipants'} // You have to name the join table
    }]
  })
  .then(function(conference) {
      // Here you will have the conference with the list of participants

  });

如果你想使用 LAZY 加载,sequelize 为你实现它,你只需要调用以下方法:
// Obtain the participant LAZY
conference.getParticipants().then(function(participants) {
  // participants is an array of participant
})

// You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method.
conference.getParticipants({ where: 'id > 10' }).then(function(participants) {
  // participants with an id greater than 10 :)
})

// You can also only retrieve certain fields of a associated object.
conference.getParticipants({attributes: ['title']}).then(function(participants) {
    // retrieve participants with the attributes "title" and "id"
})

您可以在下一个 document 中获得对 sequelize 关系实现的引用。

关于node.js - Sequelize : 'findAll' in instance method getParticipants()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519663/

相关文章:

Node.js + mongodb : wait for query to complete

node.js - 如何在 google cloud datastore .get 上设置超时?

mysql - updateOnDuplicate 无效

qt - 是否可以将 QAbstractTableModel 与 QtQuick.Controls 中的 TableView 一起使用?

ruby-on-rails - 如何防止更新 Rails 中的单个属性?

node.js - Expressjs cookie 解析器在 cookie 中添加 j : 前缀

json - Heroku 上的 BabelJs : Couldn't find preset "env" relative to directory "/app"

node.js - 如何在时间戳上使用 Sequelize 更新 'NOW()'?

node.js - 使用 Jest、Graphql 和 Sequelize 测试数据库时如何避免 EADDRINUSE

python - 获取 Django 中模型类的调用堆栈