简体   繁体   English

Sequelize.js - “没有关联”

[英]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.我想获得一个特定用户的 object,包括所有角色内容。 Somethink like有点像

{
  id: 4,
  password: 'xxx',
  email: 'adsads@saas.com',
  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"但我得到的结果是 err.message: "role is not associated to user"

And the simple question - what's wrong?简单的问题 - 怎么了? :) :)

*to handle models I'm using sequelize-cli *处理模型我正在使用 sequelize-cli

You have to declare associations between your Models.您必须声明模型之间的关联。 If using Sequelize CLI make sure the static method associate is being called.如果使用 Sequelize CLI,请确保正在调用 static 方法关联 Example:例子:

/models.index.js /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然后是 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;

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 基于您的json,我看到每个用户只有一个角色,因此您可以在角色模型中使用belongsTo或在用户模型中使用hasOne

Should be something like this: 应该是这样的:

User.js 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 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM