V
V
vetsmen2019-08-01 18:15:37
JavaScript
vetsmen, 2019-08-01 18:15:37

How to merge 2 tables in Sequelize (Postgres)?

There are two tables:

let Cases = sequelize.define('cases', {
      title: {
         type: DataTypes.STRING,
         allowNull: false,
         unique: true
      },
      category: {
         type: DataTypes.INTEGER,
         allowNull: false,
      },
      img: {
         type: DataTypes.STRING,
         allowNull: false,
      },
      price: {
         type: DataTypes.INTEGER,
         allowNull: false
      },
      oldPrice: {
         type: DataTypes.INTEGER
      },
      counter: {
         type: DataTypes.INTEGER,
      },
      totalCounter: {
         type: DataTypes.INTEGER,
      }
   }, {
      timestamps: false
   });

let Categories = sequelize.define('categories', {
      title: {
         type: DataTypes.STRING,
         allowNull: false
      }
   }, {
      timestamps: false
   });

I need to run a query like this:
SELECT cases.*, casecategories.title AS `cat` FROM cases LEFT JOIN casecategories ON cases.category = casecategories.id;

I make such associations and request:
models.categories.hasMany(models.cases, {foreignKey: 'category'});
models.cases.belongsTo(models.categories, {foreignKey: 'id'});

  const cases2 = await models.cases.findAll({
    raw: true,
    include: [
      { model: models.categories, attributes: ['title'] }
    ],
  });

However, I am getting an error:
Error: Naming collision between attribute 'category' and association 'category' on model cases. To remedy this, change either foreignKey or as in your association definition

What's wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question