使用空引用进行一对多排序

时间:2018-12-16 07:53:46

标签: mysql database express sequelize.js

我的情况就是这样。对于给定的库存项目,将有零个或多个相关成本。所以我的Sequelize模型看起来如下。

  // StockItem Model
  const StockItem =  sequelize.define('StockItem', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    purchasedDate: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: null,
      field: 'purchased_date',
    }, {
    // Other attributes
    }, {
    paranoid: false,
    createdAt: 'created_date',
    updatedAt: 'updated_date',
    tableName: 'STOCK_ITEMS'
    });
     StockItem.associate = (models) => {
           StockItem.hasMany(models.Cost, { as: 'StockItemCosts', foreignKey: 'stock_item_id' });
     };
  });

  // Cost Model
    const Cost = sequelize.define('Cost', {
     id: {
       type: DataTypes.INTEGER,
       autoIncrement: true,
       primaryKey: true,
     },
     type: {
       type: DataTypes.STRING(50),
       allowNull: false,
     }, {
      // Other attributes
     }, {
      paranoid: false,
      createdAt: 'created_date',
      updatedAt: 'updated_date',
      tableName: 'COSTS'
    });
  });

根据我的要求,即使没有成本,我也应该能够保存库存项目。我尝试了不同的方法。但是,当我尝试节省成本时会出现以下错误:空值。我使用基于Express js的Rest API将数据保存到MySQL数据库。而且我将库存项目数据保存到数据库,如下所示:

 const stockItem = {
  ...restApiData // Data received from FE form submission.
  StockItemCosts: restApiData.costDetails, // This is null when there is no costs associated with the item.
 }
 sequelize.transaction((t) => {
    return  StockItem.create(stockItem, {
      transaction: t,
      include: [ { model: Cost, as: 'StockItemCosts' }]
    });
  }).then ((result) => {
   // console.log('result : ', result); // eslint-disable-line no-console

   // Transaction has been committed
    // result is whatever the result of the promise chain returned to the transaction callback
  }).catch((err) => {
   console.log('err : ', err); // eslint-disable-line no-console
    // Transaction has been rolled back
    // err is whatever rejected the promise chain returned to the transaction callback
  });

这是我遇到的错误。

Executing (83cc74a4-7067-44ef-8767-d0c08783a132): ROLLBACK;
err :  { SequelizeValidationError: notNull Violation: Cost.type cannot be null,
notNull Violation: Cost.cost cannot be null,
notNull Violation: Cost.createdBy cannot be null,
notNull Violation: Cost.updatedBy cannot be null

我尝试了一些约束条件:如下所示为false,但这也没有用。任何帮助,不胜感激。

StockItem.hasMany(models.Cost,{as:'StockItemCosts',foreignKey:'stock_item_id',约束条件:false});

-------------------------------------------------- ----------------更新--------------------------------- ----------------------

我根据@Praveen Kumar的评论找到了解决方案。但是,当我不花成本保存实体时,就无法获取没有相关成本的记录。由于我正在使用分页获取数据,因此无法进行其他查询来完成它。

这就是我现在的做法:

return StockItem.findAll({ include: [ { model: Cost, as: 'StockItemCosts' }] }) 

0 个答案:

没有答案