data icon indicating copy to clipboard operation
data copied to clipboard

[Feature Request] Referencing `primaryKey` of a model as opposed to the entire object

Open nojibe opened this issue 1 year ago • 0 comments

When referencing model(s), an object might be designed to only hold the primaryKey(s) of the referenced model(s). For example, Mirage when relating the models blogPost and comments,...

import { createServer, Model, hasMany } from "miragejs"

createServer({
  models: {
    blogPost: Model.extend({
      comments: hasMany(), // relation to `comments` model
    }),

    comment: Model,
  },
})

...creates several helpful keys for the association. In addition, if I wanted the association to be named differently, I could create the association like so: hasMany("different name for association here").

blogPost.commentIds // [1, 2, 3]
blogPost.commentIds = [2, 3] // updates the relationship
blogPost.comments // array of related comments
blogPost.comments = [comment1, comment2] // updates the relationship
blogPost.newComment(attrs) // new unsaved comment
blogPost.createComment(attrs) // new saved comment (comment.blogPostId is set)

nojibe avatar Oct 04 '24 15:10 nojibe