Skip to content

Add MorphOne relationship #90

Closed
@kiaking

Description

@kiaking

Let's add MorphOne relationship.

For example, a blog Post and a User may share a polymorphic relation to an Image model. Using a one-to-one polymorphic relation allows you to have a single list of unique images that are used for both blog posts and user accounts.

Below is the model definition for such models.

class User extends Model {
  static entity = 'users'

  @Num(0) id!: number
  @Str('') name!: string

  @MorphOne(() => Image, 'imageableId', 'imageableType' )
  image!: Image | null
}

class Post extends Model {
  static entity = 'posts'

  @Num(0) id!: number
  @Str('') title!: string

  @MorphOne(() => Image, 'imageableId', 'imageableType' )
  image!: Image | null
}

class Image extends Model {
  static entity = 'images'

  @Num(0) id!: number
  @Str('') url!: string
  @Num(0) imageableId!: number
  @Str(0) imageableType: string
}

Then, we fetch models like so:

userRepo.with('image').find(1)

/*
  {
    id: 1,
    name: 'John Doe',
    image: {
      id: 1,
      url: '/profile.jpg',
      imageable_id: 1,
      imageable_type: 'users'
    },
  }
*/

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions