JaeWang Lee
JaeWang Lee

Reputation: 197

one to one relation using sequelize?

    var Friend = sequelize.define('Friend', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    userId_1: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    userId_2: {
        type: DataTypes.INTEGER,
        allowNull: false
    }

and

    var User = sequelize.define('User', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }

I have models named Friend, User like above that and...

I want to one-one association that Friend has names of each user_1, user_2 along [id] in User

"userId_1": "1",
"userId_2": "2",
"user_1": {
  "name": "User1 Name"
},
"user_2": {
  "name": "User2 Name"
}

like this,

How I solve this in Node-Express using Sequelize

Upvotes: 1

Views: 2734

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58553

Define model like this :

var Friend = sequelize.define('Friend', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    userId_1: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    userId_2: {
        type: DataTypes.INTEGER,
        allowNull: false
    }
);

Friend.belongsTo(User, { as : 'user_1' , foreignKey : 'userId_1', constraints: false});
Friend.belongsTo(User, { as: 'user_2', foreignKey : 'userId_2' , constraints:false});

constraints:false depends upon user_1 and user_2 is madatory or not , if yes then you can remove it , if not then please keep it as it is.

You can get data of both user like this

Friend.findAll({
    ...
    include : [
        {
            model : User ,
            as : 'user_1' // <--------- Here is the magic
        },        {
            model : User ,
            as : 'user_2' // <--------- Here is the magic
        }
    ]
})

Upvotes: 1

TMarafon
TMarafon

Reputation: 337

In order to query Friend and access the user's name, you need to create an association of the type hasOne between those two entities.

var Friend = sequelize.define('Friend', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    }
    Friend.hasOne(User, { as: 'user_1' }); // this will add the attribute user_1Id to Friend
    Friend.hasOne(User, { as: 'user_2' }); // this will add the attribute user_2Id to Friend
}

Then you can get the User object using Friend.getUser_1()

You can find more info about hasOne association here.

Upvotes: 0

Related Questions