DEV Community

loading...

Sequelize One-to-One Example – Nodejs Association

loizenai profile image loizenai ・2 min read

https://loizenai.com/sequelize-one-to-one-example/

In the tutorial, I guide how to create Sequelize One-To-One example association models with NodeJS/Express, MySQL.

  • Technologies for Sequelize Nodejs Association One to One:
  • Nodejs
  • Express
  • Sequelize
  • MySQL

Sequelize One-to-One Example Association

Note: When calling a method such as Customer.hasOne(Address), we say that the Customer model is the source and the Address model is the target.

We define 2 models:


Customer = sequelize.define('customer', {
  /* attributes */
});

Address = sequelize.define('address', {
    /* attributes */
});

How to create One-to-One association between them?
-> Sequelize provides 2 ways:

  • belongsTo

Address.belongsTo(Customer); // Will add a customerId attribute to Address to hold the primary key value for Customer.
  • hasOne

Customer.belongsTo(Address); // Will add an attribute customerId to the Address model.

What is difference between belongsTo and hasOne?
-> hasOne inserts the association key in target model whereas BelongsTo inserts the association key in the source model.

We can create a solution by combine foreignKey and targetKey with belongsTo and hasOne relation as below code:


Customer = sequelize.define('customer', {
  uuid: {
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV1,
    primaryKey: true
  },
  /*
    more attributes
  */
});

Address = sequelize.define('address', {
    /* attributes */
});
    
Address.belongsTo(Customers, {foreignKey: 'fk_customerid', targetKey: 'uuid'});
Customers.hasOne(Address, {foreignKey: 'fk_customerid', targetKey: 'uuid'});

Foreign Key

  • In belongsTo relation, foreign key will be generated from the target model name and the target primary key name. Sequelize provides a foreignKey option to override defaultValue.

Target Key

  • The target key is the column on the target model that the foreign key column on the source model points to. In belongsTo relation, by default the target key will be the target model's primary key. Sequelize provides a targetKey option to define a custom column.

How to save it?


var customer;
Customer.create({ 
    firstname: 'Jack',
    ...
    }).then(createdCustomer => {        
        // Send created customer to client
        customer = createdCustomer;
        
        return Address.create({
            street: 'W NORMA ST',
            ...
        })
    }).then(address => {
        customer.setAddress(address)
    })
};

How to fetch entities? - Tutorial: "Sequelize One-to-One Example Association - Nodejs MySQL"

More: https://loizenai.com/sequelize-one-to-one-example/

Discussion (0)

pic
Editor guide