Pablo
Pablo

Reputation: 29519

How to create record with specifying foreign key?

I have Users and Bets tables as 1:M relations. However, I didn't want to have any Bet record without User reference.

enter image description here

So I have the following constrained relations:

Bet.belongsTo(User, {
    foreignKey: {
        allowNull: false
    }
});
User.hasMany(Bet);

This is creating foreign key in Bets which can't be null. This is how I intend to create Bet record:

User.findOne({
    where: {email: '[email protected]'}
}).then(u => {
    Bet.create({
        User: u,
        ...
    })
    .then(b => {
        console.log('done');
    });
})

Is there any way to specify User while creating Bet? I know I could do it with <foreignkey>: u.id, but I wonder if there is a way to do it on higher level, like using include and not explicitly referring to foreign key.

Upvotes: 1

Views: 37

Answers (1)

Ankh
Ankh

Reputation: 5728

In defining a relation between User and Bet you'll have gained some association methods on those models.

Using the create method you can instead create a new Bet from the User instance which will both create a new Bet in the DB and associate it to the User.

User.findOne({
    where: { email: '[email protected]' }
})
    .then(user =>
    {
        user.createBet({ ... })
            .then(bet =>
            {
                console.log('done');
            });
    });

Upvotes: 1

Related Questions