我有一个问题,我失去了时间,没有。
我有一个型号价格:
var price = sequelize.define('price', {
price_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataType.INTEGER
},
carrier_mongo_id : {
type: DataType.STRING,
require : true,
references: {
model: "carrier",
key: "carrier_mongo_id"
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
value: {
type: DataType.DECIMAL
}
});
我有其他型号Carrier:
var carrier = sequelize.define('carrier', {
carrier_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Datatype.INTEGER
},
carrier_mongo_id: {
type: Datatype.STRING,
require : true
},
name: {
type: Datatype.STRING,
require : true
}
});
并进行如下查询:
carrierModel.hasMany(priceModel, {foreignKey: 'carrier_mongo_id'});
carrierModel.findAll({ include: [{ model: priceModel , required: true }] }).then(function(result){
var aCarriers = new Array();
result.forEach(function(carreteiro){
aCarriers.push(carreteiro.dataValues);
});
console.log(aCarriers);
}).catch(function(err){
console.log(err);
});
我的查询是:
SELECT
`carrier`.`carrier_id`,
`carrier`.`carrier_mongo_id`,
`carrier`.`name`,
`prices`.`price_id` AS `prices.price_id`,
`prices`.`carrier_mongo_id` AS `prices.carrier_mongo_id`,
`prices`.`value` AS `prices.value`
FROM
`carrier` AS `carrier`
INNER JOIN `price` AS `prices` ON `carrier`.`carrier_id` = `prices`.`carrier_mongo_id`
但我需要这个SQL查询:
SELECT
`carrier`.`carrier_id`,
`carrier`.`carrier_mongo_id`,
`carrier`.`name`,
`prices`.`price_id` AS `prices.price_id`,
`prices`.`carrier_mongo_id` AS `prices.carrier_mongo_id`,
`prices`.`value` AS `prices.value`
FROM
`carrier` AS `carrier`
INNER JOIN `price` AS `prices` ON `carrier`.`carrier_mongo_id` = `prices`.`carrier_mongo_id`
我知道我可以使用这个方法Sequelize.query(...),但我的问题是:
如何使用Sequelize模型进行此查询
TKS
答案 0 :(得分:0)
我为我的案例找到了解决方案=)
修复是更新CarrierModel为primaryKey设置carrier_mongo_id
........................
carrier_mongo_id : {
type: DataType.STRING,
require : true,
primaryKey: true,
references: {
model: "carrier",
key: "carrier_mongo_id"
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
.....................
查询如下:
carreteiroModel.hasMany(precoModel, {foreignKey: 'carreteiro_mongo_id', otherKey: 'carreteiro_mongo_id'});
carreteiroModel.findAll({ include: [{ model: precoModel , required: true }] }).
then(function(result){ ...});
请你评论:),