使用空引用对一对多进行续集

ee7vknir  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(344)

我的设想是这样的。对于一个给定的库存项目,将有零或更多的成本与之相关。所以我的续集模型如下。

// 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'
    });
  });

根据我的要求,我应该能够节省库存项目,即使它没有成本。我试过不同的方法。但当我试图节省成本时,我得到了以下错误:一个空值。我使用基于expressjs的restapi将数据保存到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,但也不起作用。非常感谢您的帮助。
hasmany(models.cost,{as:'stockitemcosts',foreignkey:'stock\u item\u id',constraints:false});

dkqlctbz

dkqlctbz2#


我根据@praveen kumar的评论找到了一个解决方案。但是,当我保存实体而没有成本时,我无法获取那些没有相关成本的记录。由于我用分页方式获取数据,所以无法使用不同的查询来完成。
我现在就是这样做的:

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

相关问题