File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -268,6 +268,38 @@ export async function generateModelString(
268
268
}\n\n`
269
269
}
270
270
271
+ if ( relationType === 'morphType' && relationCount === 'many' ) {
272
+ const morphName = relation . relationName || `${ formattedModelName } able`
273
+
274
+ // Add field to the model for relationship access
275
+ fieldString += `${ snakeCase ( morphName ) } ?: ${ modelRelation } Model[] | undefined\n`
276
+
277
+ // Add getter for the relationship
278
+ getFields += `get ${ snakeCase ( morphName ) } ():${ modelRelation } Model[] | undefined {
279
+ return this.attributes.${ snakeCase ( morphName ) }
280
+ }\n\n`
281
+
282
+ // Add relationship to JSON output
283
+ jsonRelations += `${ snakeCase ( morphName ) } : this.${ snakeCase ( morphName ) } ,\n`
284
+
285
+ // Add method to retrieve the polymorphic related models
286
+ relationMethods += `
287
+ async ${ morphName } (): Promise<${ modelRelation } Model[]> {
288
+ if (this.id === undefined)
289
+ throw new HttpError(500, 'Relation Error!')
290
+
291
+ const models = await ${ modelRelation }
292
+ .where('${ relation . modelKey } ', '=', '${ modelName } ')
293
+ .where('${ relation . foreignKey } ', '=', this.id)
294
+ .get()
295
+
296
+ if (!models || !models.length)
297
+ return []
298
+
299
+ return models
300
+ }\n\n`
301
+ }
302
+
271
303
if ( relationType === 'hasType' && relationCount === 'one' ) {
272
304
const relationName = relation . relationName || formattedModelRelation
273
305
Original file line number Diff line number Diff line change @@ -28,6 +28,8 @@ export interface MorphOne<T = string> extends BaseRelation {
28
28
id ?: string
29
29
}
30
30
31
+ export interface MorphMany < T = string > extends MorphOne < T > { }
32
+
31
33
export interface HasMany < T = string > extends Array < Relation < T > > { }
32
34
export interface BelongsTo < T = string > extends Array < Relation < T > > { }
33
35
@@ -180,6 +182,8 @@ export interface ModelOptions extends Base {
180
182
181
183
morphOne ?: MorphOne < ModelNames > | ModelNames
182
184
185
+ morphMany ?: MorphMany < ModelNames > [ ] | ModelNames [ ]
186
+
183
187
morphTo ?: MorphTo
184
188
185
189
scopes ?: {
You can’t perform that action at this time.
0 commit comments