Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js - "is not associated to"

I have some issue with getting full data from db. That are my models:

User

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('user', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'ID'
        },
        password: {
            type: DataTypes.STRING(255),
            allowNull: false,
            field: 'password'
        },
        email: {
            type: DataTypes.STRING(255),
            allowNull: false,
            unique: true,
            field: 'email'
        },
        roleId: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            references: {
                model: 'role',
                key: 'ID'
            },
            field: 'role_id'
        }
    }, {
        timestamps: false,
        tableName: 'user'
    });
};

Role

module.exports = function(sequelize, DataTypes) {
return sequelize.define('role', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        field: 'ID'
    },
    name: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        field: 'name'
    },
    description: {
        type: DataTypes.STRING(255),
        allowNull: false,
        field: 'description'
    },
    permission: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        field: 'permission'
    }
}, {
    timestamps: false,
    tableName: 'role',
});};

I want to get object of one specific user including all role content. Somethink like

{
  id: 4,
  password: 'xxx',
  email: '[email protected]',
  role: {
     id: 2,
     name: 'admin'
     description: 'ipsum ssaffa',
     permission: 30
  }
}

So I'm using:

User.findOne( { where: { id: req.userId }, include: [ Role ] } ).then( user =>{...});

but I get in the result err.message: "role is not associated to user"

And the simple question - what's wrong ? :)

*to handle models I'm using sequelize-cli

like image 308
The4ECH Avatar asked Jun 13 '18 16:06

The4ECH


2 Answers

You get this error because you didn't add associate between the models

base on your json I see that each user only has one role, so you can either use belongsTo in role model or hasOne in user model

Should be something like this:

User.js

module.exports = function(sequelize, DataTypes) {
var user =  sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        field: 'ID'
    },
    password: {
        type: DataTypes.STRING(255),
        allowNull: false,
        field: 'password'
    },
    email: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        field: 'email'
    },
    roleId: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        references: {
            model: 'role',
            key: 'ID'
        },
        field: 'role_id'
    }
}, {
    timestamps: false,
    tableName: 'user'
});
    user.associate = function(models) {
        user.hasOne(models.role, {foreignKey: 'id',sourceKey: 'roleId'});

    }
    return user;
};

Role.js

module.exports = function(sequelize, DataTypes) {
    var role = sequelize.define('role', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        field: 'ID'
    },
    name: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        field: 'name'
    },
    description: {
        type: DataTypes.STRING(255),
        allowNull: false,
        field: 'description'
    },
    permission: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        field: 'permission'
    }
    }, {
        timestamps: false,
        tableName: 'role',
    });
    role.associate = function(models) {
        user.belongsTo(models.role, {foreignKey: 'id'});

    }
    return role;
};
like image 139
feiiiiii Avatar answered Oct 16 '22 19:10

feiiiiii


You have to declare associations between your Models. If using Sequelize CLI make sure the static method associate is being called. Example:

/models.index.js

const Category  = require('./Category');
const Product = require('./Product');
const ProductTag = require('./ProductTag');
const Tag = require('./Tag');

Category.associate({Product});
Product.associate({Category,Tag});
Tag.associate({Product});

module.exports={Category,Product,ProductTag,Tag};

and then the association in Category.js

'use strict';
const {Model,DataTypes} = require('sequelize');
const sequelize = require('../config/connection.js');

    class Category extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method.
         */
        static associate({Product}) {
            // define association here
            console.log('Category associated with: Product');
            this.hasMany(Product, {
                foreignKey: 'category_id',
                onDelete: 'CASCADE'
            });
        }
    }

    Category.init({
        category_id: {type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
        category_name: {type: DataTypes.STRING, allowNull: false}
    }, {
        sequelize,
        timestamps: false,
        freezeTableName: true,
        underscored: true,
        modelName: "Category",
    });

module.exports = Category;
like image 1
Gianni Fontanot Avatar answered Oct 16 '22 20:10

Gianni Fontanot