[英]Sequelize many to many order association table by custom column
i am building a desktop app with electron and MySQL我正在使用 electron 和 MySQL 构建桌面应用程序
1- how to order association table results by custom column in many to many association 1-如何在多对多关联中按自定义列排序关联表结果
//Company model
const Company = sequelize.define("Company", {
name: {
type: DataTypes.STRING,
allowNull: false,
},
});
//Branch Model
const Branch = sequelize.define("Branch", {
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
},
});
//Associations
//join table
const CompanyBranch = sequelize.define("CompanyBranch",
{
order: {
type: DataTypes.INTEGER,
},
});
Branch.belongsToMany(Company, {
through: CompanyBranch,
as: "Branches",
});
Company.belongsToMany(Branch, {
through: CompanyBranch,
});
2- how to map results to the correct shape instead of having nested object. 2-如何将 map 结果变为正确的形状,而不是嵌套 object。
NB: in JavaScript Branch.order //=> undefined
注意:在 JavaScript
Branch.order //=> undefined
My query我的查询
//query
const companies = await Company.findAll({include: [Branch]})
//result
{
//company attrs
Branches: [
{id: 1, name: "branch 1", description: null,
CompanyBranch: { CompanyId: 1, ActivityId: 1, BranchId: 1, order: 1}]
}
The result i want to have我想要的结果
{
//company attrs
Branches: [
{id: 1, name: "branch 1", description: null, order: 1}]
}
You can try to use the attributes
option to include the CompanyBranch.order
field as the order
field of Branch:您可以尝试使用
attributes
选项将CompanyBranch.order
字段包含为 Branch 的order
字段:
const companies = await Company.findAll({
include: [
{
model: Branch,
attributes: ['id', 'name', 'description', [Sequelize.col('CompanyBranch.order'), 'order']]
}
]})
Upd.更新。 If you wish to order by
CompanyBranch.order
then it's better to add associations from Company
to CompanyBranch
and from CompanyBranch
to Branch
( hasMany
and belongsTo
respectively) and use them like this:如果您希望通过
CompanyBranch.order
订购,那么最好添加从Company
到CompanyBranch
以及从CompanyBranch
到Branch
的关联(分别为hasMany
和belongsTo
)并像这样使用它们:
Company.hasMany(CompanyBranch);
CompanyBranch.belongsTo(Branch);
...
const companies = await Company.findAll({
include: [
{
model: CompanyBranch,
attributes: ['order'],
include: [{
model: Branch,
attributes: ['id', 'name', 'description']
},
}],
order: [['CompanyBranch', 'order', 'ASC']]
})
That way you can also indicate what fields you wish to get from CompanyBranch
and from Branch
even on the CompanyBranch
level using notation like ['AssociationName.field', 'alias']
这样,您还可以使用
['AssociationName.field', 'alias']
类的符号指示您希望从CompanyBranch
和Branch
甚至在CompanyBranch
级别上获取哪些字段
the solution is to use Sequelize literal to order by custom join table column解决方案是使用 Sequelize 文字按自定义连接表列排序
const companies = await Company.findAll({
include: [Branch],
order: [[Sequelize.literal("`Branches->CompanyBranch`.`order`"), "ASC"]]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.