Jam*_*len 6 javascript mysql sequelize.js
所以我想为这5个表建立关系并做一个findAll并从每个表中获取一些信息.抱歉丑陋的桌子显示
产品表
| Field | Type | Null | Key | Default | Extra |
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| typeId | int(11) unsigned | NO | MUL | NULL | |
| image | varchar(255) | YES | | NULL | |
| desc | text | YES | | NULL | |
| price | float | YES | | NULL | |
| stock | int(11) | YES | | NULL | |
Run Code Online (Sandbox Code Playgroud)
类型表
| Field | Type | Null | Key | Default | Extra |
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
Run Code Online (Sandbox Code Playgroud)
规格表
| Field | Type | Null | Key | Default | Extra |
| productId | int(11) unsigned | NO | PRI | NULL | |
| name | text | YES | | NULL | |
Run Code Online (Sandbox Code Playgroud)
JctProductColors表
| Field | Type | Null | Key | Default | Extra |
| productId | int(11) unsigned | NO | PRI | NULL | |
| colorId | int(11) unsigned | NO | PRI | NULL | |
Run Code Online (Sandbox Code Playgroud)
颜色表
| Field | Type | Null | Key | Default | Extra |
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
Run Code Online (Sandbox Code Playgroud)
这就是我现在的关系
Product.belongsTo(Spec, {
"foreignKey": "id",
"through": {
model: "ProductSpec",
unique: false
},
"constraints": false
});
Spec.belongsTo(Product, {
"foreignKey": "productId",
"through": {
model: "ProductSpec",
unique: false
},
"constraints": false
});
Type.belongsToMany(Product, {
"constraints": false,
"foreignKey": "id",
"through": {
model: "ProductType",
unique: false
}
});
Product.belongsTo(Type, {
"constraints": false,
"foreignKey": "typeId",
"through": {
model: jctProductColor,
unique: false
}
});
Product.belongsToMany(Color, {
"constraints": false,
"foreignKey": "productId",
"through": {
model: jctProductColor,
unique: false
}
});
Color.belongsToMany(Product, {
"constraints": false,
"foreignKey": "colorId",
"through": {
model: jctProductColor,
unique: false
}
});Run Code Online (Sandbox Code Playgroud)
我想创建一个findAll来显示它
select types.name as Type, products.image, products.desc, products.price, products.stock, specs.name as Specs, colors.name as Color from products
join types
on types.id = products.typeId
join specs
on products.id = specs.productId
join jctproductcolors
on jctproductcolors.productId = products.id
join colors
on colors.id = jctproductcolors.colorid
where products.id = :id
Run Code Online (Sandbox Code Playgroud)
我知道你在一年前问过这个问题,但我一直在寻找同样的东西,发现你的问题没有得到解答。
你可以这样做:
models.Product.findAll({
attributes: ['image', 'desc', 'price', 'stock'],
include: [{
model: models.Type,
attributes: [['name', 'Type']]
}, {
model: models.Specs,
attributes: [['name', 'Specs']]
}, {
model: models.JctProductColors,
include: [{
model: models.Color,
attributes: [['name', 'Color']]
}]
}
],
where: {
id: id
}
});
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看此处:http :
//docs.sequelizejs.com/en/latest/docs/querying/
| 归档时间: |
|
| 查看次数: |
3408 次 |
| 最近记录: |