基于 Sequelize 中包含的数据进行查询

Query based on included data in Sequelize

提问人:wazzaday 提问时间:9/27/2017 最后编辑:wazzaday 更新时间:6/19/2023 访问量:1586

问:

我为有自我联想的人准备了一张桌子,这样人们就可以有父母/孩子/堂兄弟姐妹/等等。

const People = sequelize.define('People', {
  gender: Sequelize.STRING,
  name: Sequelize.STRING,
  age: Sequelize.INTEGER
})

const Relationships = sequelize.define('Relationships')
Items.belongsToMany(Items, { through: Relationships, as: 'relationships' })

我希望能够以两种方式选择数据:

1. 选择年满 21 岁的人的所有关系

// Returns all of johns relatives who are 21
return People.findOne({
  where: { name: 'John' },
  include: [{
    required: false,
    model: Items,
    as: 'relationships',
    where: { age: 21 }
  }]
})

2. 选择所有有 21 岁亲戚的人。这将需要接受多个查询,例如: 选择所有有 21 岁或/和男性亲戚的人。

有什么想法吗?

节点.js PostgreSQL 续集.js

评论

0赞 Ellebkey 10/4/2017
您需要找到所有 21 岁和男性的人吗?如果您需要 OR 使用$or请尝试where { age:21 , gender: 'Male'where: { $or [ {age: 21}, {gender:'Male'} ] }
0赞 Md Nazmul Hossain 10/10/2017
使用 People.findAll()
0赞 Ryan W 10/28/2017
你能分享一下你定义自关联的代码吗?
0赞 shivshankar 11/13/2017
Items.belongsToMany(Items, { through: Relationships, as: 'relationships', foreignKey: 'field_name' })
0赞 gwintrob 12/20/2017
可能的重复项 是否可以使用 sequelize 按关联表中的属性过滤查询?

答:

0赞 jlh 5/3/2018 #1

这里有一些完整的代码可以玩,我希望它对某人有用。请注意,在这个例子中,关系不是互惠的,这意味着如果约翰与玛丽有关系,那么玛丽不会自动与约翰建立关系(这更像是约翰跟随玛丽的情况)。但它仍然可以作为如何使用显式联接表进行自关联的示例。

let Sequelize = require('sequelize');
let sequelize = new Sequelize('test', 'test', 'test', {dialect: 'mysql'});

let Person = sequelize.define('Person', {
    name: Sequelize.STRING,
    gender: Sequelize.STRING,
    age: Sequelize.INTEGER
});

let PersonRelationship = sequelize.define('PersonRelationship' /* , more fields could be defined here */);

Person.belongsToMany(Person, {as: 'Relationships', through: PersonRelationship, foreignKey: 'from'});
Person.belongsToMany(Person, {as: 'ReverseRelationships', through: PersonRelationship, foreignKey: 'to'});

let john, mary;

sequelize.sync()
    .then(() => Person.create({name: 'John', gender: 'm', age: 25}))
    .then(p => john = p)
    .then(() => Person.create({name: 'Mary', gender: 'f', age: 21}))
    .then(p => mary = p)
    .then(() => john.addRelationship(mary))
    .then(() => john.getRelationships({where: {age: 21}}))
    .then(relationships => {
        for (let relationship of relationships) {
            console.log('Found relationship:', relationship.name);
        }
    });
0赞 Hassan Rehan 6/19/2023 #2

对于第一个问题:选择 21 岁的人的所有关系。您的查询是正确的。

return People.findOne({
  where: { name: 'John' },
  include: [{
    required: false,
    model: People,
    as: 'relationships',
    where: { age: 21 }
  }]
});

对于第二个查询:选择所有有 21 岁或/和男性关系的人。

People.findAll({
  include: [{
    required: true,
    model: People,
    as: 'relationships',
    where: {
      $or: [
        { age: 21 },
        { gender: 'Male' }
      ]
    }
  }]
});

希望这对任何看到该帖子的人有所帮助