graphiti-api / spraypaint.js

Graphiti Client / Javascript ORM / JSONAPI
MIT License
108 stars 69 forks source link

create record and associate it to another record in one request #94

Closed bilouw closed 3 years ago

bilouw commented 3 years ago

Hi,

Let's say i want to create a Post and associate it to an already created Comment. (in my example, Comment belongs_to Post and Post has_one Comment) This is what i'm doing:

let post = new Post({ comment: new Comment}) post.comment.id = commentIdToAssociate post.save({ with: 'comment.id' })

This code will create a new comment associated to the post with method: "create". I don't want to create this comment, i want to associate it to my post (method: "update")

I want this kind of body:

"relationships": {
    "comment": {
        "data": {
            "id": "64520319-03be-4c29-b86b-199c1038ba23",
            "type": " comments",
            "method": "update"
        }
    },
}

How can i do that ?

Thanks.

richmolj commented 3 years ago

Try this:

let comment = new Comment({ id: "123" })
comment.isPersisted = true
let post = new Post({ comment })
post.save({ with: 'comment.id' })
bilouw commented 3 years ago

Just what i needed ! I did not understand that i should use isPersisted attributes to specify that the record already exist in DB.

Thanks for your help !

Also: Graphiti & Spraypaint are great tools to develop !

richmolj commented 3 years ago

Thanks @bilouw !