序列化-创建包含的外键返回null

时间:2019-08-18 07:16:56

标签: javascript express sequelize.js

使用create include插入时,外键返回null,但是其余数据从传递的对象中保存。

这是我的交易模型:


module.exports = (sequelize, DataTypes) => {
    const Transaction = sequelize.define('transactions', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            primaryKey: true
        },
        receiptNumber: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        supCustID: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        userID: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        type: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        status: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        createdAt: {
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
      allowNull: false
        },
        updatedAt: {
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
      allowNull: false
        }
    }, {
        tableName: 'transactions'
  });

  Transaction.associate = models => {
    Transaction.Order = Transaction.hasMany(models.Order, {
      as: 'Orders',
      foreignKey: 'transaction_id'
    })

    Transaction.SupCust = Transaction.belongsTo(models.SupCust, {
      as: 'SupCust',
      foreginKey: 'supCustID'
    })

    Transaction.User = Transaction.belongsTo(models.User, {
      as: 'User',
      foreginKey: 'userID'
    })
  }

  return Transaction;
};

订单模型:

/* jshint indent: 1 */

module.exports = (sequelize, DataTypes) => {
    const Order = sequelize.define('orders', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            primaryKey: true
        },
        transaction_id: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        itemID: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        qty: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        itemCost: {
            type: DataTypes.REAL,
            allowNull: true
        },
        discount: {
            type: DataTypes.REAL,
            allowNull: true
        },
        totalAmount: {
            type: DataTypes.REAL,
            allowNull: true
        }
    }, {
    tableName: 'orders',
    timestamps: false,
    hooks: {
      afterValidate: (Order) => {
        console.log(Order)
      },
    }
  });

  Order.associate = models => {
    Order.belongsTo(models.Transaction, {
      as: 'Transactions',
      foreignKey: 'transaction_id'
    })

    Order.belongsTo(models.ItemList, {
      as: 'Items',
      foreignKey: 'itemID'
    })
  }

  return Order;
};

执行插入数据的代码:

return await models.Transaction
    .findOne({ where: { id: values.id || -1 } })
    .then(async function (obj) {
        if(obj) { // update
          return await obj.update(values, {individualHooks: true});
        }
        else { // insert
          const {id, ...payload} = values
          return await models.Transaction.create(payload, {
            include: [{ 
              association: models.Transaction.Order 
            }], 
          });
        }
    })

控制台结果:

Executing (default): INSERT INTO `transactions` (`id`,`receiptNumber`,`supCustID`,`userID`,`type`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);

Executing (default): INSERT INTO `orders` (`id`,`transaction_id`,`itemID`,`qty`,`itemCost`) VALUES ($1,$2,$3,$4,$5);

从挂钩上的订单模型控制台日志:

dataValues:
   { id: null,
     itemID: 1008,
     itemCost: '2',
     qty: '1',
     transaction_id: null },

为什么这总是空的?我在想什么吗?

1 个答案:

答案 0 :(得分:1)

通过在我的交易模型上添加autoincrement属性来解决此问题。

id: {
     type: DataTypes.INTEGER,
     allowNull: true,
     primaryKey: true,
     autoIncrement: true
}