Relationships
Relationships connect your models together. Adminmate works without them, but they unlock useful features: references displayed as links to the related record, and the related records listed in a dedicated tab of the item page.
If you used the CLI on a SQL database, the relationships found in your foreign keys have been added for you. Otherwise, declare them as shown below.
Use the Sequelize associations: hasMany, hasOne and belongsTo. For example, a user has many cars:
module.exports = (sequelize, DataTypes) => { const User = sequelize.define('users', { // ... });
User.associate = models => { User.hasMany(models.cars, { foreignKey: 'user_id' }); };
return User;};module.exports = (sequelize, DataTypes) => { const Car = sequelize.define('cars', { // ... });
Car.associate = models => { Car.belongsTo(models.users, { foreignKey: 'user_id' }); };
return Car;};Use the ref option on an ObjectId field, with the name of the referenced model. For example, a car belongs to a user:
module.exports = mongoose => { const schema = mongoose.Schema({ // ... user_id: { type: mongoose.Schema.Types.ObjectId, ref: 'users' } });
return mongoose.model('cars', schema, 'cars');};Dynamic references with refPath are supported too.