我为有自我交往的人提供了一张 table ,这样人们就可以拥有 parent / child /表兄弟/等。
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岁或男性的亲戚的人。
有任何想法吗?
最佳答案
这是一些完整的代码,我希望可以对某人有用。请注意,在此示例中,关系不是对等的,这意味着如果John与Mary有关系,则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);
}
});