在Sequelize中如何匹配include中的唯一键和外键而不是主键和外键

时间:2018-05-14 11:11:21

标签: sql-server node.js sequelize.js

有两个表[弓形细节和项目细节]。我实际上完成了两个表之间的关联

 var BomDetail = sequelize.define('BomDetail', {
        bomId: {
            type: DataTypes.STRING,
            field: 'bom_id',
            unique: true
        },
        createdBy: {
            type: DataTypes.STRING,
            field: 'created_by'
     },
BomDetail.hasMany(models.ItemDetail, {
     foreignKey: 'bomId',
     sourceKey: 'bomId',
     onDelete: 'cascade'
});

var ItemDetail = sequelize.define('ItemDetail', {
        itemId: {
            type: DataTypes.STRING,
            field: 'item_id',
            unique: true
        },
        holdDate: {
            type: DataTypes.DATE,
            field: 'hold_date',
        },
        bomId: {
            type: DataTypes.STRING,
            field: 'bom_id'
        },
ItemDetail.associate = function(models) {
        ItemDetail.belongsTo(models.BomDetail, {
            foreignKey: 'bomId',
            targetKey: 'bomId',
            onDelete: 'cascade'
        });
    };

当我做的时候

Models.ItemDetail.findAll({
include: {
model: Models.BomDetail
}
})

项目细节内的bomdetail正常结果将会出现

{
"id": 3,
"itemId": "2397saf8enaeflk8",
"productId": "afsggfg14fhg43t",
"productName": "Siemens meter",
"quantity": 3,
"followUpDate": "2018-05-15T18:30:00.000Z",
"leadTime": 10,
"releaseDate": "2018-05-20T18:30:00.000Z",
"holdDate": "2018-05-31T18:30:00.000Z",
"bomId": "azcpspp02_07141700_07_00_M00",
"status": "hold",
"created_at": "2018-05-14T09:20:15.658Z",
"updated_at": "2018-05-14T09:20:15.658Z",
"BomDetail": {
"id": 50,
"bomId": "azcpspp02_07141700_07_00_M00",
"createdBy": "azcpspp02",
"createdByName": "Siemens BLR -nry85322",
"bomCreatedDate": "2018-02-26T00:00:00.000Z",
"soldToAcc": "30000006",
"status": "hold",
"created_at": "2018-05-11T11:58:46.267Z",
"updated_at": "2018-05-11T11:58:46.267Z"
}
},

但是当我做的时候

Models.BomDetail.findAll({
include: {
model: Models.ItemDetail:
}
})

错误会来.. 转换nvarchar值时转换失败' azcpspp02_07141700_07_00_M00'数据类型int。

它比较了BomDetail表中的sequelize和ItemDetail的外键生成的primay键 喜欢 ... LEFT OUTER JOIN [lta_item_detail] AS [ItemDetails] ON [BomDetail]。[id] = [ItemDetails]。[bom_id];

但我想比较BomDetail表的唯一键(bomId)和ItemDetail表(BomId)的相应外键..

(即)...... LEFT OUTER JOIN [lta_item_detail] AS [ItemDetails] ON [BomDetail]。[bom_id] = [ItemDetails]。[bom_id];

我该怎么做?

2 个答案:

答案 0 :(得分:0)

尝试从ItemDetail模型中删除bomId并执行必需的false以应用左外连接。

Models.BomDetail.findAll({
    include: {
       model: Models.ItemDetail,
       required : false
    }
});

答案 1 :(得分:0)

尝试将源密钥定义为字段名称,以便该关联可以相应地工作。

BomDetail.hasMany(models.ItemDetail, {
    foreignKey: 'bomId',
    sourceKey: 'bom_id',
    onDelete: 'cascade'
});