How to add child row in related table?? (Sequelzie N:M Relationship)

二次信任 提交于 2021-01-29 11:15:42

问题


In my program, I'd like to create a new post named Column contains of many categoris. Also, a category can contain of many posts.(N:M)

So I tried to add a category to the post, but it failed. Here is the code I've tried: However, no errors are output to the log.

for(var i in column_categorys) {
    const category = await Category.findOrCreate({
      where : {
        category_name: column_categorys[i],
      }
    })
    .then(resolve => {
      return resolve;
    })
    .catch(function(error) {
      isFail = true;
      return null;
    });

    await column.addCategory(
      category.id,
      { through:
        { selfGranted: false }
      }
    )
    .catch(err => {
      console.log(err);
    });
  }

column_info.js

const Sequelize = require('sequelize');

module.exports = class Column extends Sequelize.Model {
  static init(sequelize) {
    return super.init({
      column_title: {
        type: Sequelize.STRING(200),
        allowNull: false,
        unique: true,
      },
      column_content_text: {
        type: Sequelize.STRING(10000),
        allowNull: false,
      },
      column_content_html: {
        type: Sequelize.STRING(10000),
      },
      column_thumbnail_url: {
        type: Sequelize.STRING(300),
      },
    }, {
      sequelize,
      timestamps: true,
      underscored: true,
      modelName: 'Column',
      tableName: 'columns',
      paranoid: true,
      charset: 'utf8',
      collate: 'utf8_general_ci',
    });
  }

  static associate(db) {
    db.Column.belongsToMany(db.Category, {
      through: 'ColumnCategory',
      unique: false,
    });
    db.Column.belongsToMany(db.Tag, {
      through: 'ColumnTag',
      unique: false,
    });
  }
};

category_info.js

const Sequelize = require('sequelize');

module.exports = class Category extends Sequelize.Model {
  static init(sequelize) {
    return super.init({
      category_name: {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true,
      },
    }, {
      sequelize,
      timestamps: false,
      underscored: true,
      modelName: 'Category',
      tableName: 'categorys',
      paranoid: false,
      charset: 'utf8',
      collate: 'utf8_general_ci',
    });
  }

  static associate(db) {
    db.Category.belongsToMany(db.Column, {
      through: 'ColumnCategory',
      unique: false,
    });
  }
};

model/index.js

const Sequelize = require('sequelize');
const User = require('./user');
const Baby = require('./baby_info');
const UserCase = require('./user_case');
const Column = require('./column_info');
const Tag = require('./tag_info');
const Category = require('./category_info');

const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config')[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);

db.sequelize = sequelize;

db.User = User;
db.Baby = Baby;
db.UserCase = UserCase;
db.Column = Column;
db.Tag = Tag;
db.Category = Category;

User.init(sequelize);
Baby.init(sequelize);
UserCase.init(sequelize);
Column.init(sequelize);
Tag.init(sequelize);
Category.init(sequelize);

User.associate(db);
Baby.associate(db);
UserCase.associate(db);
Column.associate(db);
Tag.associate(db);
Category.associate(db);

module.exports = db;

Could you tell me what part of this code I've used relationship queries incorrectly?

Latest Version

let getColumn = async function(req, res) {
  const result = await Column.findOne({
    where: {
      column_title: req.body.column_name,
    },
    include: Category,
  });

  res.send({result: result});
}

let insertColumn = async function(req, res) {
  let isFail = false;

  let column_title = req.body.title;
  let column_content_text = req.body.contentText;
  let column_content_html = req.body.contentHTML;
  let column_categorys = req.body.categoris;
  let column_tags = req.body.tags;

  let column_thumbnail_url = process.env.CDN_ENDPOINT;
  column_thumbnail_url += column_title;
  column_thumbnail_url += '/';
  column_thumbnail_url += '0.png';

  await sequelize.transaction(async transaction => {
    try {
      const column = await Column.create({
        column_title: column_title,
        column_content_text: column_content_text,
        column_content_html: column_content_html,
        column_thumbnail_url: column_thumbnail_url,
      }, {transaction: transaction});

      for(var i in column_categorys) {
        const category = await Category.findOrCreate({
          where : {
            category_name: column_categorys[i],
          },
          transaction,
        });
        await column.addCategory(
          category.id,
          { transaction },
        );
      }

      for(var j in column_tags) {
        const tag = await Tag.findOrCreate({
          where : {
            tag_name: column_tags[j],
          },
          transaction,
        });

        await column.addTag(
          tag.id,
          { transaction },
        );
      }
    } catch (err) {
      console.log(err);
      isFail = true;
    }
  });

  if(isFail) {
    res.json({
      responseCode: 404,
      responseMsg: 'Fail'
    });
  } else {
    res.json({
      responseCode: 400,
      responseMsg: 'Success'
    });
  }
}

The responseCode is 400, and there is no error message. But Nothing is in ColumnCategory.

And next one is the logging message.

0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): START TRANSACTION;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): INSERT INTO `columns` (`id`,`column_title`,`column_content_text`,`column_content_html`,`column_thumbnail_url`,`created_at`,`updated_at`) VALUES (DEFAULT,?,?,?,?,?,?);
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SAVEPOINT `9904bd92-1a06-4f58-853f-9517d560ca50-sp-1`;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SELECT `id`, `category_name` FROM `categorys` AS `Category` WHERE `Category`.`category_name` = 'category1';
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SAVEPOINT `9904bd92-1a06-4f58-853f-9517d560ca50-sp-2`;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SELECT `id`, `category_name` FROM `categorys` AS `Category` WHERE `Category`.`category_name` = 'category2';
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SAVEPOINT `9904bd92-1a06-4f58-853f-9517d560ca50-sp-3`;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SELECT `id`, `tag_name` FROM `tags` AS `Tag` WHERE `Tag`.`tag_name` = 'tag1' LIMIT 1;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SAVEPOINT `9904bd92-1a06-4f58-853f-9517d560ca50-sp-4`;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): SELECT `id`, `tag_name` FROM `tags` AS `Tag` WHERE `Tag`.`tag_name` = 'tag2' LIMIT 1;
0|app  | 21-01-03 11:27:28: Executing (9904bd92-1a06-4f58-853f-9517d560ca50): COMMIT;
0|app  | 21-01-03 11:27:28: POST /api/column 200 55.857 ms - 73

回答1:


The troublemaker was FindOrCreate!

it returns Object, boolean value(it means a new row is created)

so, the result has to be divided into two variables.

For example,

const [category, created] = await Category.findOrCreate()

After fixing this part in the latest version, it worked fine!

Of course, addCategory(category), addCategory(category.id) both worked!




回答2:


You shouldn't use then/catch along with await, use try/catch to catch any errors:

try {
  for(columnCategory of column_categorys) {
      const category = await Category.findOrCreate({
        where : {
          category_name: column_categorys[i],
        }
      })
      await column.addCategory(
        category.id,
        { through:
          { selfGranted: false }
        }
      );
  }
} catch (err) {
  console.log(err);
}

Also I recommend to use a transaction when you perform several CRUD-operations. That way your modified data will be consistent. This could be achieved like this:

await sequelize.transaction(async transaction => {
  try {
    for(columnCategory of column_categorys) {
        const category = await Category.findOrCreate({
          where : {
            category_name: column_categorys[i],
          },
          transaction
        })
        await column.addCategory(
          category.id,
          { through:
            { selfGranted: false },
            transaction
          }
        );
    }
  } catch (err) {
    console.log(err);
  }
});


来源:https://stackoverflow.com/questions/65543213/how-to-add-child-row-in-related-table-sequelzie-nm-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!