Add relationships

Adding the relationships

As Lumber generates a back office application from the database schema, it only creates belongsTo relationships, based on all your foreign keys. Please note that some ORMs do not create foreign key constraints. This means that in some cases, you will have to add belongsTo relationships manually. Lastly, as databases don’t have the notion of inverse relationships, you will need to add hasMany or hasOne relationships manually.

All Lumber-based back offices use the Sequelize ORM to manage data models. Check out their documentation if you need more information.

Adding a BelongsTo relationship

On our Live Demo example, the Address model has a foreignKey customer_id that points to the Customer. In other words, an addressbelongsTo a customer. We’ve declared this relationship in the file models/addresses.js

/models/addresses.js
module.exports = (sequelize, DataTypes) => {
let Address = sequelize.define('addresses', {
// ...
}, {
// ...
});
Address.associate = (models) => {
Address.belongsTo(models.customers);
};
return Address;
};

Adding a HasOne relationship

HasOne relationships are the opposite of BelongsTo relationships. Taking the same example as before, the opposite of the Address belongsTo a Customer is simply a Customer hasOne Address.

/models/customers.js
module.exports = (sequelize, DataTypes) => {
var Customer = sequelize.define('customers', {
// ...
}, {
// ...
});
Customer.associate = (models) => {
Customer.hasOne(models.addresses);
};
return Customer;
};

Adding a HasMany relationship

The Customer has one Address but can have multiple Orders. In that case, we have to use HasMany instead of HasOne relationships

/models/customers.js
module.exports = (sequelize, DataTypes) => {
var Customer = sequelize.define('customers', {
// ...
}, {
// ...
});
Customer.associate = (models) => {
Customer.hasMany(models.orders);
};
return Customer;
};