Thomas Ham
Thomas Ham

Reputation: 80

How to create with association in Sequelize

I have two Sequelize models that are associated with a belongsTo relationship. I would like to create an instance of user_sources when user is created but I am struggling to accomplish it.

model_user:

const User = sequelize.define('user', {
    email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    }
}, {
    tableName: 'users'
})

model_user_sources:

const UserSources = sequelize.define('user_sources', {
    abcNews: {
        type: Sequelize.BOOLEAN,
    },
    bbcNews: {
        type: Sequelize.BOOLEAN,
    }
}, {
    tableName: 'user_sources'
})

UserSources.belongsTo(User)

Both models are initialized and the tables are created in the database properly. According to the Sequelize documentation I should be able to create both with association in a single query like so:

User
    .create({
        email: user.email,
        password: user.password,
    }, {
        include: UserSources
    })

However, only the user is created. The user_sources item does not get created in the table.

Unfortunately the documentation only shows an example of creating a parent model from a child model but not the other way around. I have tried several different methods such as using a hasOne association, adding model/association options into the include, putting data into the create method, etc. But I feel as though I am not grasping the concept properly.

Would appreciate if someone could shed some light on my problem. Thanks.

Upvotes: 1

Views: 6206

Answers (1)

Lin Du
Lin Du

Reputation: 102207

"sequelize": "^5.21.3". Here are three ways to create data records for User and UserSources model with associations. Besides, we keep adding the foreign key constraint using userId to user_sources table.

E.g.

index.js:

import { sequelize } from '../../db';
import Sequelize from 'sequelize';

const User = sequelize.define(
  'user',
  {
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false,
    },
  },
  {
    tableName: 'users',
  },
);

const UserSources = sequelize.define(
  'user_source',
  {
    abcNews: {
      type: Sequelize.BOOLEAN,
    },
    bbcNews: {
      type: Sequelize.BOOLEAN,
    },
  },
  {
    tableName: 'user_sources',
  },
);

UserSources.belongsTo(User);

// User.UserSources = User.hasOne(UserSources);
// User.hasOne(UserSources);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // 1. User.UserSources = User.hasOne(UserSources);
    // await User.create(
    //   {
    //     email: '[email protected]',
    //     password: '123',
    //     user_source: {
    //       abcNews: true,
    //       bbcNews: true,
    //     },
    //   },
    //   {
    //     include: [
    //       {
    //         association: User.UserSources,
    //       },
    //     ],
    //   },
    // );

    // 2. User.hasOne(UserSources);
    // await User.create(
    //   {
    //     email: '[email protected]',
    //     password: '123',
    //     user_source: {
    //       abcNews: true,
    //       bbcNews: true,
    //     },
    //   },
    //   {
    //     include: [UserSources],
    //   },
    // );

    // 3. UserSources.belongsTo(User);
    await UserSources.create(
      {
        abcNews: true,
        bbcNews: true,
        user: {
          email: '[email protected]',
          password: '123',
        },
      },
      {
        include: [User],
      },
    );
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

After executing the above code, check the data records in the database:

node-sequelize-examples=# select * from "users";
 id |       email       | password
----+-------------------+----------
  1 | [email protected] | 123
(1 row)

node-sequelize-examples=# select * from "user_sources";
 id | abcNews | bbcNews | userId
----+---------+---------+--------
  1 | t       | t       |      1
(1 row)

The data records are created as expected.

Upvotes: 2

Related Questions