fullstack-graphql-angular icon indicating copy to clipboard operation
fullstack-graphql-angular copied to clipboard

Issues with associations when adding a new model

Open ghost opened this issue 7 years ago • 0 comments

Hi, first at all, Thanks for the great example that you have created. I have learnt a lot from it. I just wondering how would you deal with the following scenario?

In you thoughts model you add a new field call userId and then create a new model for users, the idea behind this is to get all the thoughts and also link the user that created the thought as an object.

thoughts { id userId name thought user(id:userId) { id firstname lastname } }

I have created the user model and the associations but I have been struggling a bit to make it work.

---- User Model ----

`//Models const models = require('./../models'); const MODEL_NAME = 'User';

exports.default = function( sequelize, DataTypes ) {

if ( !sequelize || !DataTypes ) {
    throw new Error( MODEL_NAME + ' Model must be imported using sequelize.import(\'path/to/' + MODEL_NAME + '.js\'');
}

const definition = {
    id : {
        type 			: DataTypes.INTEGER,
        autoIncrement 	: true,
        primaryKey      : true,
        autoIncrement   : true,
        unique          : true
    },
    firstname 	: DataTypes.STRING,
    lastname 	: DataTypes.STRING,
    password    : {
    	type :  DataTypes.STRING,
    	validate: {
			notEmpty: true
		}
    },
    email       : {
        type 		: DataTypes.STRING,
        allowNull	: false,
        unique : {
            args    : true,
            msg     : 'Oops. Looks like you already have an account with this email address. Please try to login.',
            fields  : [ sequelize.fn('lower', sequelize.col('email')) ]
        },            
    },        
    createdBy    		 : DataTypes.INTEGER,
    createdDate  		 : DataTypes.INTEGER
};

const User = sequelize.define( MODEL_NAME, definition, {
    tableName : 'users',
    freezeTableName: true
});

// Class Method
User.associate = function ( m ) {
    // associations can be defined here
    m.User.hasMany( m.Thought, { as : 'thoughts', foreignKey : 'id' });
};

 /**
 * @name: getUserByEmail
 *
 * @description: Get user by email
 * @param: {email}
 * @return {object}
 * @api public
 */
User.getUserByEmail = function ( email ) {
    return this.find({
        where: { email : email }
    });
};

/**
 * @name: getAll
 *
 * @description: Get all users
 * @param: {}
 * @return {object}
 * @api public
 */
User.getAll = function () {

    return this.findAll({
        include: [
            { model : models.default.Thought, as : 'thoughts', required : true },
        ]
    });
};

return User;

}; `

--- Thought Model ----

`const models = require ( './../models' ); const MODEL_NAME = 'Thought';

// Thought Model exports.default = function ( sequelize, dataTypes ) {

if ( !sequelize || !dataTypes ) {
    throw new Error( MODEL_NAME + ' Model must be imported using sequelize.import(\'path/to/' + MODEL_NAME + '.js\'');
}

const Thought = sequelize.define( MODEL_NAME, {
    userId: {
        type: dataTypes.INTEGER
    },
    name: {
        type: dataTypes.STRING
    },
    thought: {
        type: dataTypes.TEXT
    }
},
{
    hooks: {},
    freezeTableName: true,
    tableName : 'thoughts'
});


// Class Method
Thought.associate = function ( m ) {
    // associations can be defined here
    m.Thought.belongsTo(  m.User, { as : 'user', foreignKey: 'userId' });
};

/**
 * @name: getAll
 *
 * @description: Get all Thoughts
 * @param: {}
 * @return {object}
 * @api public
 */
Thought.getAll = function () {
    return this.findAll({
        include: [{ 
            model       : models.default.User, 
            as          : 'user', 
            required    : true 
        }]
    });
};

return Thought;

};`

ghost avatar Apr 09 '18 07:04 ghost