A.js :
A.associate = models => {
A.hasMany(models.B, { foreignKey: 'A_id' });
A.hasMany(models.C, { foreignKey: 'A_id' });
A.hasMany(models.D, { foreignKey: 'A_id' });
};
A.findOne({
where: { id: _id },
include: [ B, C, D ],
});
B.js :
B.associate = models => {
B.belongsTo(models.A, { foreignKey: 'A_id' });
};
C.js :
C.associate = models => {
C.belongsTo(models.A, { foreignKey: 'A_id' });
};
D.js :
D.associate = models => {
D.belongsTo(models.A, { foreignKey: 'A_id' });
};
DB :
A TABLE
id:1 name: A
B TABLE
A_id:1 name: B1
A_id:1 name: B2
blabla...
A :: findOne的结果:
A
id:1 blabla...
B
A_id:1 name: B1
A_id:1 name: B2 -> NO FIND B2
我要搜索“单个A记录”和“多个B,C,D记录”。我怎样才能做到这一点? 续集中的关联是如此混乱。
感谢您的帮助!
routes / A.js
router.get('/:id', (req, res) => {
const { A } = require('../models');
A.getById(req.params.id)
.then(record => {
console.log(record[0].Bs);
});
});
models / A.js
A.associate = models => {
A.belongsTo(models.User, {foreignKey: 'userId'});
A.hasMany(models.B, {foreignKey: 'A_Id'});
A.hasMany(models.C, {foreignKey: 'A_Id'});
};
A.getById = _id => {
const { B, C } = require('../models');
return A.findAll({
where: { id: _id },
include: [ B, C ],
});
};
models / B.js
B.associate = models => {
B.belongsTo(models.A, { foreignKey: 'A_Id' });
};
执行的查询
SELECT `A`.`id`, `A`.`userId`, `A`.`name`,
`Bs`.`A_Id` AS `Bs.A_Id`, `Bs`.`name` AS `Bs.name`,
`Cs`.`A_Id` AS `Cs.A_Id`, `Cs`.`name` AS `Cs.name`
FROM `As` AS `A`
LEFT OUTER JOIN `Bs` AS `Bs` ON `A`.`id` = `Bs`.`A_Id`
LEFT OUTER JOIN `Cs` AS `Cs` ON `A`.`id` = `Cs`.`A_Id`
WHERE `A`.`id` = '1'
登录路线/A.js
[ B {
dataValues: { A_Id: 1, name: 'Name1' },
_previousDataValues: ...
...
} ]
但是执行查询的结果是多行。 (在数据库客户端程序中)