@@ -31,6 +31,12 @@ module.exports = class DiscoveryGenerator extends ArtifactGenerator {
3131 default : true ,
3232 } ) ;
3333
34+ this . option ( 'relations' , {
35+ type : Boolean ,
36+ description : g . f ( 'Discover and create relations' ) ,
37+ default : false ,
38+ } ) ;
39+
3440 this . option ( 'schema' , {
3541 type : String ,
3642 description : g . f ( 'Schema to discover' ) ,
@@ -289,6 +295,7 @@ module.exports = class DiscoveryGenerator extends ArtifactGenerator {
289295 {
290296 schema : modelInfo . owner ,
291297 disableCamelCase : this . artifactInfo . disableCamelCase ,
298+ associations : this . options . relations ,
292299 } ,
293300 ) ;
294301 if ( this . options . optionalId ) {
@@ -336,6 +343,46 @@ module.exports = class DiscoveryGenerator extends ArtifactGenerator {
336343 ) ;
337344 debug ( `Writing: ${ fullPath } ` ) ;
338345
346+ if ( this . options . relations ) {
347+ const relationImports = [ ] ;
348+ const relationDestinationImports = [ ] ;
349+ const foreignKeys = { } ;
350+ for ( const relationName in templateData . settings . relations ) {
351+ const relation = templateData . settings . relations [ relationName ] ;
352+ const targetModel = this . artifactInfo . modelDefinitions . find (
353+ model => model . name === relation . model ,
354+ ) ;
355+ // If targetModel is not in discovered models, skip creating relation
356+ if ( targetModel ) {
357+ Object . assign ( templateData . properties [ relation . foreignKey ] , {
358+ relation,
359+ } ) ;
360+ relationImports . push ( relation . type ) ;
361+ relationDestinationImports . push ( relation . model ) ;
362+
363+ foreignKeys [ relationName ] = { } ;
364+ Object . assign ( foreignKeys [ relationName ] , {
365+ name : relationName ,
366+ entity : relation . model ,
367+ entityKey : Object . entries ( targetModel . properties ) . find (
368+ x => x ?. [ 1 ] . id === 1 ,
369+ ) ?. [ 0 ] ,
370+ foreignKey : relation . foreignKey ,
371+ } ) ;
372+ }
373+ }
374+ templateData . relationImports = relationImports ;
375+ templateData . relationDestinationImports = relationDestinationImports ;
376+ // Delete relation from modelSettings
377+ delete templateData . settings . relations ;
378+ if ( Object . keys ( foreignKeys ) ?. length > 0 ) {
379+ Object . assign ( templateData . settings , { foreignKeys} ) ;
380+ }
381+ templateData . modelSettings = utils . stringifyModelSettings (
382+ templateData . settings ,
383+ ) ;
384+ }
385+
339386 this . copyTemplatedFiles (
340387 modelDiscoverer . MODEL_TEMPLATE_PATH ,
341388 fullPath ,
0 commit comments