diff --git a/packages/strapi-bookshelf/lib/index.js b/packages/strapi-bookshelf/lib/index.js index df935aec88..ebfa6321bf 100755 --- a/packages/strapi-bookshelf/lib/index.js +++ b/packages/strapi-bookshelf/lib/index.js @@ -236,6 +236,7 @@ module.exports = function(strapi) { const association = definition.associations .filter(association => association.nature.toLowerCase().indexOf('morph') !== -1) .filter(association => association.alias === path || association.via === path)[0]; + if (association) { // Override on polymorphic path only. if (_.isString(path) && path === association.via) { @@ -252,7 +253,11 @@ module.exports = function(strapi) { strapi.plugins[association.plugin].models[association.collection || association.model]: strapi.models[association.collection || association.model]; - return `${association.alias}.${model.collectionName}`; + return { + [`${association.alias}.${model.collectionName}`]: function(query) { + query.orderBy('created_at', 'desc'); + } + }; } } diff --git a/packages/strapi-plugin-content-manager/config/queries/bookshelf.js b/packages/strapi-plugin-content-manager/config/queries/bookshelf.js index 706cb3b649..f09885db4e 100755 --- a/packages/strapi-plugin-content-manager/config/queries/bookshelf.js +++ b/packages/strapi-plugin-content-manager/config/queries/bookshelf.js @@ -218,6 +218,28 @@ module.exports = { strapi.plugins[obj.source].models[obj.ref]: strapi.models[obj.ref]; + // Remove existing relationship because only one file + // can be related to this field. + if (association.nature === 'manyMorphToOne') { + return virtualFields.push( + module.exports.removeRelationMorph.call(this, { + alias: association.alias, + ref: model.collectionName, + refId: obj.refId, + field: obj.field + }) + .then(() => + module.exports.addRelationMorph.call(this, { + id: response[this.primaryKey], + alias: association.alias, + ref: model.collectionName, + refId: obj.refId, + field: obj.field + }) + ) + ); + } + virtualFields.push(module.exports.addRelationMorph.call(this, { id: response[this.primaryKey], alias: association.alias, @@ -386,12 +408,12 @@ module.exports = { removeRelationMorph: async function (params) { return await this.morph.forge() - .where({ + .where(_.omitBy({ [`${this.collectionName}_id`]: params.id, [`${params.alias}_id`]: params.refId, [`${params.alias}_type`]: params.ref, field: params.field - }) + }, _.isEmpty)) .destroy(); } };