Himmators
Himmators

Reputation: 15006

Create associated object?

I'm trying to grasp how to work with associated objects.

I have two objects

UserAttributes

    var sequelize = require('../database.js').sequelize,
        Sequelize = require('../database.js').Sequelize,
        User = sequelize.models.user,
        UserAttribute = sequelize.define('userAttributes', {
            name:       Sequelize.STRING,
            value:      Sequelize.STRING,
        });

    UserAttribute.belongsTo(User);
    module.exports = UserAttribute;

User

User = sequelize.define('user', {},{
    classMethods: {
        createRider: function(params) {
            var values = [],
                userAttributes = sequelize.models.userAttributes,
                user = User.build(),
                name = userAttributes.build({name: 'name', value: 'params.name'}),
                fbprofile = userAttributes.build({name: 'fbprofile', value: 'params.fbprofile'}),
                phone = userAttributes.build({name: 'phone', value: 'params.phone'});

            user.save().then((user) => {
                console.log(user);
                user.adduserAttributes([name, fbprofile, phone]);
            });


        }
    }
});

For some reason adduserAttributes does not work. This is all the docs I've found on this.

http://docs.sequelizejs.com/en/2.0/api/associations/

Upvotes: 1

Views: 156

Answers (1)

Sushant
Sushant

Reputation: 1414

BelongsTo is a 1:1 relationship. This mean you can associate only one row to other table row.

Since its singular realtion setter method name will be setUserAttribute(), (More docs)

If you want to link multiple rows to a single row in another table you should use hasMany

Upvotes: 2

Related Questions