strapi/packages/strapi-hook-bookshelf/lib/generate-group-relations.js

79 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-07-01 16:59:14 +02:00
'use strict';
const pluralize = require('pluralize');
const createGroupModels = async ({ model, definition, ORM, GLOBALS }) => {
2019-07-01 16:59:14 +02:00
const { collectionName, primaryKey } = definition;
const groupAttributes = Object.keys(definition.attributes).filter(
key => definition.attributes[key].type === 'group'
);
if (groupAttributes.length > 0) {
// create group model
const joinTable = `${collectionName}_groups`;
const joinColumn = `${pluralize.singular(collectionName)}_${primaryKey}`;
const joinModel = ORM.Model.extend({
2019-07-08 18:35:39 +02:00
tableName: joinTable,
2019-07-01 16:59:14 +02:00
slice() {
return this.morphTo(
'slice',
...groupAttributes.map(key => {
const groupKey = definition.attributes[key].group;
return GLOBALS[strapi.groups[groupKey].globalId];
})
);
},
});
2019-07-09 18:20:36 +02:00
joinModel.foreignKey = joinColumn;
2019-07-11 16:00:33 +02:00
definition.groupsJoinModel = joinModel;
2019-07-09 18:20:36 +02:00
2019-07-01 16:59:14 +02:00
groupAttributes.forEach(name => {
2019-07-09 18:20:36 +02:00
model[name] = function relation() {
2019-07-01 16:59:14 +02:00
return this.hasMany(joinModel).query(qb => {
qb.where('field', name).orderBy('order');
});
};
});
}
};
const createGroupJoinTables = async ({ definition, ORM }) => {
const { collectionName, primaryKey } = definition;
const groupAttributes = Object.keys(definition.attributes).filter(
key => definition.attributes[key].type === 'group'
);
if (groupAttributes.length > 0) {
const joinTable = `${collectionName}_groups`;
const joinColumn = `${pluralize.singular(collectionName)}_${primaryKey}`;
2019-07-01 16:59:14 +02:00
if (await ORM.knex.schema.hasTable(joinTable)) return;
await ORM.knex.schema.createTable(joinTable, table => {
2019-07-01 16:59:14 +02:00
table.increments();
table.string('field').notNullable();
table
.integer('order')
.unsigned()
.notNullable();
table.string('slice_type').notNullable();
table.integer('slice_id').notNullable();
table.integer(joinColumn).notNullable();
2019-07-01 16:59:14 +02:00
table
.foreign(joinColumn)
.references(primaryKey)
.inTable(collectionName)
.onDelete('CASCADE');
});
}
};
module.exports = {
createGroupModels,
createGroupJoinTables,
};