Skip to content

Commit 4569d80

Browse files
chore: wip
1 parent 1381ee3 commit 4569d80

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

storage/framework/core/orm/src/generate.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,38 @@ export async function generateModelString(
268268
}\n\n`
269269
}
270270

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+
271303
if (relationType === 'hasType' && relationCount === 'one') {
272304
const relationName = relation.relationName || formattedModelRelation
273305

storage/framework/core/types/src/model.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ export interface MorphOne<T = string> extends BaseRelation {
2828
id?: string
2929
}
3030

31+
export interface MorphMany<T = string> extends MorphOne<T> {}
32+
3133
export interface HasMany<T = string> extends Array<Relation<T>> {}
3234
export interface BelongsTo<T = string> extends Array<Relation<T>> {}
3335

@@ -180,6 +182,8 @@ export interface ModelOptions extends Base {
180182

181183
morphOne?: MorphOne<ModelNames> | ModelNames
182184

185+
morphMany?: MorphMany<ModelNames>[] | ModelNames[]
186+
183187
morphTo?: MorphTo
184188

185189
scopes?: {

0 commit comments

Comments
 (0)