Commercial ORM - part 2

Pre-requisites

Learning Objectives

Understand how to add relationships representing FOREIGN KEY constraints to commercial ORM implementations.

Lesson

Adding foreign key constraints

/* To connect tables in Sequelize your model definitions simply need to specify 
their relationships using the `hasMany` or `belongsTo` functions. For example, we
simply add the following lines to the Restaurant class */

Restaurant.hasMany(Menu, {as: 'menus', foreignKey: 'restaurant_id'})
Menu.belongsTo(Restaurant, {foreignKey: 'restaurant_id'})

/* Sequelize will do all the hard work of creating the new foreign key columns! 
It will also create accessor methods such as `getMenus` and `addMenu` - 
it uses the `as` value to determine the accessor name */
TODO

Testing relationships

We can test the relationships have been setup correctly using the following code:

const {sequelize} = require('./sequelize_index');
const {Restaurant} = require('./Restaurant');
const {Menu} = require('./Menu');

describe('Relationships', () => {
    beforeAll(async () => {
        await sequelize.sync({ force: true });
    })
    
    test('restaurants have menus', async () => {
        // note that Sequelize is build using promises, so we use async await
        const restaurant = await Restaurant.create({name: 'Ronalds', image: 'http://some.image.url'})
        const menu = await Menu.create({title: 'set 1'});
        await restaurant.addMenu(menu);
        const menus = await restaurant.getMenus();
        expect(menus[0].title).toBe('set 1');
    })

})
TODO

Assignment

  1. Extend your solution from the previous assignment by configuring the relationships between the Restaurant, Menu and Menu Item model classes.
  2. Write unit tests that prove all relationships are all correctly connected (i.e. that Restaurants have Menus and Menus have MenuItems)
  3. Ensure your database is populated with the restaurant JSON data
  4. Commit your code into Github and share the link with your coach for review

Assignment extension tasks

Additional resources