续集,关联返回时出现问题

发布于 2024-11-15 11:06:18 字数 854 浏览 0 评论 0原文

我目前正在尝试 Sequelize 并有两个对象,一个 PersonPosition,当获取人员列表时我想获得他们的位置。

模型:

var User = sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING 
});

var Position = sequelize.define('position', {
    name: Sequelize.STRING,
    affiliation: Sequelize.STRING
});

Position.hasMany(User, { foreignKey : 'position_id' });
User.belongsTo(Position, { foreignKey : 'position_id'});

我的查询:

User.findAll({ fetchAssociations: true }, function(results) {
    //I've tried doing some work in here, but haven't found the correct procedure. 
}).on('success', function(results) {
    res.render('users', {
        title: 'user page',
        users: results
    });
});

查看日志它根本不会查询 Person 。我需要使用查询链吗?从文档中我发现它似乎应该自动获取关联。

I'm currently experimenting with Sequelize and have two objects, a Person and Position, When getting a list of persons I want to get their position.

models:

var User = sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING 
});

var Position = sequelize.define('position', {
    name: Sequelize.STRING,
    affiliation: Sequelize.STRING
});

Position.hasMany(User, { foreignKey : 'position_id' });
User.belongsTo(Position, { foreignKey : 'position_id'});

My query:

User.findAll({ fetchAssociations: true }, function(results) {
    //I've tried doing some work in here, but haven't found the correct procedure. 
}).on('success', function(results) {
    res.render('users', {
        title: 'user page',
        users: results
    });
});

Watching the log it never queries Person at all. Do I need to use queryChaining? From the documentation I was able to find it appeared it should auto fetch associations.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

望笑 2024-11-22 11:06:18

从 2013 年 4 月的 v1.7.0 开始,您只需将关联扩展到:

Position.hasMany(User, {foreignKey : 'position_id', as: 'User'});
User.belongsTo(Position, {foreignKey : 'position_id', as: 'Posit'});

然后查找具有关联职位的所有用户

User.findAll({
      include: [{
        model: Position, as: 'Posit'
      }]
}).success(function(match) {
    // your logic
});

From April 2013 in v1.7.0 you need just to expand your Associations to:

Position.hasMany(User, {foreignKey : 'position_id', as: 'User'});
User.belongsTo(Position, {foreignKey : 'position_id', as: 'Posit'});

and then find all Users with associated Positions

User.findAll({
      include: [{
        model: Position, as: 'Posit'
      }]
}).success(function(match) {
    // your logic
});
維他命╮ 2024-11-22 11:06:18

好的,这里是如何解决您的问题的完整示例(是的,这很糟糕):

User.findAll().on('success', function(users) {
  var chainer = new Sequelize.Utils.QueryChainer
    , _users  = []

  users.forEach(function(u) {
    var emitter = new Sequelize.Utils.CustomEventEmitter(function() {
      u.getPosition().on('success', function(pos) {
        _users.push({user: u, position: pos})
        emitter.emit('success')
      })
    })
    chainer.add(emitter.run())
  })
  chainer.run().on('success', function() {
    res.render('users', {
      title: 'user page',
      users: _users
    })
  })
})

这将首先获取所有用户,然后获取每个用户的位置并将其保存在 _users 数组中。然后它渲染页面。它没有经过测试,但应该可以解决问题。

Ok here a complete example how to fix your problem (and yeah that's crap):

User.findAll().on('success', function(users) {
  var chainer = new Sequelize.Utils.QueryChainer
    , _users  = []

  users.forEach(function(u) {
    var emitter = new Sequelize.Utils.CustomEventEmitter(function() {
      u.getPosition().on('success', function(pos) {
        _users.push({user: u, position: pos})
        emitter.emit('success')
      })
    })
    chainer.add(emitter.run())
  })
  chainer.run().on('success', function() {
    res.render('users', {
      title: 'user page',
      users: _users
    })
  })
})

This will first get all the users, then get the position of each user and save them in the _users-array. Afterwards it renders the page. It's not tested but should do the trick.

得不到的就毁灭 2024-11-22 11:06:18

由于我重写了 1.0 的sequelize,因此我删除了对 fetchAssociations 的支持。我将在接下来的几周内添加它。但是让我们看一下您的代码:

您正在使用类似下划线的列名称,因此您可能希望对自动生成的列使用下划线选项: http://www.sequelizejs.com/?active=usage#usage -->向下滚动一点或搜索下划线。这可能会为您节省belongsTo/hasMany 的选项。

你想用 findAll 做的事情是:就像这样:

User.findAll().on('success', function(users) {
  // asd
})

正如我刚刚注意到的......获取所有关联的对象有点棘手:D 现在就这么多。希望有帮助。

since I rewrote sequelize for 1.0 I removed the support of fetchAssociations. I will add it in the next weeks. But let's take a look at your code:

You are using underscore-like column names, so you probably want to use the underscore option for automatically generated columns: http://www.sequelizejs.com/?active=usage#usage --> scroll a bit down or search for underscore. This might save you the options for belongsTo/hasMany.

What you want to do with findAll is smth. like this:

User.findAll().on('success', function(users) {
  // asd
})

And as I just noticed... it's somewhat tricky to get all associated objects :D So much for now. Hope that helped.

旧竹 2024-11-22 11:06:18

这允许序列化 json 以用于模型的任何操作。阅读它,很好,我认为这是最好的方法

sequelize-virtual-fields

// define models 
var Person = sequelize.define('Person', { name: Sequelize.STRING });
var Task = sequelize.define('Task', {
name: Sequelize.STRING,
nameWithPerson: {
    type: Sequelize.VIRTUAL,
    get: function() { return this.name + ' (' + this.Person.name + ')' }
    attributes: [ 'name' ],
    include: [ { model: Person, attributes: [ 'name' ] } ],
    order: [ ['name'], [ Person, 'name' ] ]
}
});

// define associations 
Task.belongsTo(Person);
Person.hasMany(Task);

// activate virtual fields functionality 
sequelize.initVirtualFields();

This allow serialize a json for anywhere action about a model. Read it, very well, i think that is the best way

sequelize-virtual-fields

// define models 
var Person = sequelize.define('Person', { name: Sequelize.STRING });
var Task = sequelize.define('Task', {
name: Sequelize.STRING,
nameWithPerson: {
    type: Sequelize.VIRTUAL,
    get: function() { return this.name + ' (' + this.Person.name + ')' }
    attributes: [ 'name' ],
    include: [ { model: Person, attributes: [ 'name' ] } ],
    order: [ ['name'], [ Person, 'name' ] ]
}
});

// define associations 
Task.belongsTo(Person);
Person.hasMany(Task);

// activate virtual fields functionality 
sequelize.initVirtualFields();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文