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

zbq4xfa0  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(158)

我有一个表的人与自我协会,所以人们可以有父母/孩子/表兄弟姐妹/等。

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岁或/和男性亲属的人。
有什么想法吗

waxmsbnn

waxmsbnn1#

这里有一些完整的代码,我希望它对某人有用。注意,在这个示例中,关系不是相互的,这意味着如果John与玛丽有关系,则Mary不会自动也与John有关系(这更像是John跟随Mary的情况)。但它仍然是如何使用显式连接表进行自关联的示例。

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);
        }
    });
brgchamk

brgchamk2#

关于第一个问题:选择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' }
      ]
    }
  }]
});

希望这将有助于任何人谁遇到的职位

相关问题