Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MorphOne relationship #90

Closed
kiaking opened this issue Nov 1, 2021 · 0 comments · Fixed by #91
Closed

Add MorphOne relationship #90

kiaking opened this issue Nov 1, 2021 · 0 comments · Fixed by #91
Labels
enhancement New feature or request

Comments

@kiaking
Copy link
Member

kiaking commented Nov 1, 2021

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'
    },
  }
*/
@kiaking kiaking added the enhancement New feature or request label Nov 1, 2021
@kiaking kiaking added this to the v1.0.0-alpha.1 milestone Nov 1, 2021
@ryandialpad ryandialpad mentioned this issue Nov 2, 2021
10 tasks
kiaking added a commit that referenced this issue Nov 10, 2021
close #90

Co-authored-by: Kia King Ishii <kia.king.08@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant