From 0b0ea7540261c62bd7a8bea12eda11b3363f7318 Mon Sep 17 00:00:00 2001 From: Adrien Lepoutre Date: Mon, 2 Apr 2018 17:50:03 -0400 Subject: [PATCH] ISSUE 825 - Losing OneToOne relation in the content manager - Fixes #825 --- .../config/queries/mongoose.js | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/strapi-plugin-content-manager/config/queries/mongoose.js b/packages/strapi-plugin-content-manager/config/queries/mongoose.js index c346228ad2..9a173a8e7c 100755 --- a/packages/strapi-plugin-content-manager/config/queries/mongoose.js +++ b/packages/strapi-plugin-content-manager/config/queries/mongoose.js @@ -85,11 +85,11 @@ module.exports = { } // Remove previous relationship asynchronously if it exists. - virtualFields.push( + let promise = new Promise(resolve => { strapi.query(details.model || details.collection, details.plugin).findOne({ id : recordId }) .then(record => { if (record && _.isObject(record[details.via])) { - return module.exports.update.call(this, { + module.exports.update.call(this, { id: record[details.via][this.primaryKey] || record[details.via].id, values: { [current]: null @@ -97,20 +97,34 @@ module.exports = { parseRelationships: false }); } - - return Promise.resolve(); + resolve() }) - ); + }) + virtualFields.push(promise); - // Update the record on the other side. + // Updating the new relations // When params.values[current] is null this means that we are removing the relation. - virtualFields.push(strapi.query(details.model || details.collection, details.plugin).update({ - id: recordId, - values: { - [details.via]: _.isNull(params.values[current]) ? null : value[this.primaryKey] || value.id || value._id - }, - parseRelationships: false - })); + promise.then(response => { + // Recreate relation on the first side + virtualFields.push(strapi.query(details.model || details.collection, details.plugin).update({ + id: recordId, + values: { + [details.via]: _.isNull(params.values[current]) ? null : value[this.primaryKey] || value.id || value._id + }, + parseRelationships: false + })); + + // Recreate relation on the other side if the value is not null + if (!_.isNull(params.values[current])) { + module.exports.update.call(this, { + id: value[this.primaryKey] || value.id || value._id, + values: { + [current]: recordId + }, + parseRelationships: false + }); + } + }); acc[current] = _.isNull(params.values[current]) ? null : value[current]; }