Sequelize Associantions

Asked

Viewed 173 times

1

I have 2 models:

user Features:

const DataTypes = require('sequelize');
const database = require('../config/dbconnection');
const user= require('./user');

const user_features = database.define('user_features', {
    id: {
      type: DataTypes.INTEGER(6),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER(6),
      references: 'USERS',
      referencesKey: 'user_id',
      allowNull: true
    },
    {
      text:{
          type: "LONGBLOB",
          allowNull: true
      }
    },
    {
       timestamps: false
    });

    user_features.belongsTo(user);
    module.exports = user_features;

users:

const DataTypes = require('sequelize');
const database = require('../config/dbconnection');

const users = database.define('users', {
    id: {
      type: DataTypes.INTEGER(6),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name {
      type: DataTypes.STRING(45)
    }
 },
 {
   timestamps: false
 });

 module.exports = users;

and on the console shows the following error:

Error: user_features.belongsTo called with something that's not a subclass of Sequelize.Model

I need to make the association between these tables so in the business rule I can make a select in the database and bring this information.

Currently I’m doing select so:

model.sequelize.query('SELECT NAME, TEXT FROM USERS LEFT JOIN USER_FEATURES ON USERS.ID = USER_FEATURES.USER_ID')

but I want to standardize the price and I wanted to use the ORM:

 getAll = (req, res, next) => model.findByPk(req.params.id,
            {
                attributes: ['NAME', 'TEXT']       
            })
            .then((result) => {
                res.send(result);
            })
            .catch(error => console.log('repository getById error: ' + error));

How could I make this association?

1 answer

0

Friend, if it was a Model sequelize class you would have to extend it to Model, I believe that why Sequelize is not understanding that user_features is a sequelize model. Here is an example of the documentation:

sequelize.define('modelName', {
  columnA: {
      type: Sequelize.BOOLEAN,
      validate: {
        is: ["[a-z]",'i'],        // will only allow letters
        max: 23,                  // only allow values <= 23
        isIn: {
          args: [['en', 'zh']],
          msg: "Must be English or Chinese"
        }
      },
      field: 'column_a'
  },
  columnB: Sequelize.STRING,
  columnC: 'MY VERY OWN COLUMN TYPE'
});

sequelize.models.modelName

Note that at the end there is the following code: sequelize.models.modelName

Browser other questions tagged

You are not signed in. Login or sign up in order to post.