diff --git a/packages/cli/generators/relation/index.js b/packages/cli/generators/relation/index.js index 0c7cb5703e50..fbdd6409dfc1 100644 --- a/packages/cli/generators/relation/index.js +++ b/packages/cli/generators/relation/index.js @@ -697,6 +697,17 @@ module.exports = class RelationGenerator extends ArtifactGenerator { ), }, ]).then(props => { + if ( + props.relationName === this.artifactInfo.foreignKeyName || + this.artifactInfo.relationName === this.artifactInfo.foreignKeyName + ) { + /* istanbul ignore next */ + return this.exit( + new Error( + `relation name ${props.relationName} cannot be the same as foreign key name ${this.artifactInfo.foreignKeyName}.`, + ), + ); + } debug(`props after relation name prompt: ${inspect(props)}`); // checks if the relation name already exists this.artifactInfo.srcRepositoryFile = path.resolve( diff --git a/packages/cli/test/integration/generators/relation.belongs-to.integration.js b/packages/cli/test/integration/generators/relation.belongs-to.integration.js index b3a89f045d71..0bf1e0376a30 100644 --- a/packages/cli/test/integration/generators/relation.belongs-to.integration.js +++ b/packages/cli/test/integration/generators/relation.belongs-to.integration.js @@ -58,6 +58,34 @@ describe('lb4 relation', /** @this {Mocha.Suite} */ function () { ).to.be.rejectedWith(/No models found/); }); + it('rejects relation when relation name is the same as foreign key name', async () => { + await sandbox.reset(); + const prompt = { + relationType: 'belongsTo', + sourceModel: 'Order', + destinationModel: 'Customer', + foreignKeyName: 'customerId', + relationName: 'customerId', // intentionally same as foreignKeyName + }; + + return expect( + testUtils + .executeGenerator(generator) + .inDir(sandbox.path, () => + testUtils.givenLBProject(sandbox.path, { + additionalFiles: SANDBOX_FILES, + }), + ) + .withOptions(options) + .withPrompts(prompt), + // Now that the bug is fixed, both values interpolate and we can assert the full message + ).to.be.rejectedWith( + new RegExp( + `relation name ${prompt.relationName} cannot be the same as foreign key name ${prompt.foreignKeyName}`, + ), + ); + }); + context('generates model relation with default values', () => { const promptArray = [ {