-
Notifications
You must be signed in to change notification settings - Fork 23
Creating and saving
To save a Coloquent model, e.g. an object artist of type Artist, do
artist.save();This query may do two things, based on if artist has an ID set prior to calling save()
- If
artisthas an ID set (i.e.artist.getId()would not returnnull), then this would yield an HTTP PATCH query. If noArtistwith the ID is found in the backend, this query would fail. - If
artistdoes not have an ID set, this query would yield an HTTP POST query, creating a newArtistin the backend.
If however you use client-generated ID's, you may want to force a HTTP POST request when you have a model's ID set, as the ID being set does not imply that the model exists on the server side. To force a HTTP POST, do
artist.create();Like any Coloquent query, save() returns a Promise, and it will pass a SaveResponse to the callback you register, e.g.
artist
.save()
.then(function(SaveResponse response) {
let savedArtist: Artist = response.getModel();
});Now savedArtist is the same as artist, except after it has been saved. In case artist does not have an ID set -making artist.save() create a new Artist in the backend- then savedArtist comes with the new ID that was created for artist. One can also directly obtain the new ID with getModelId():
artist
.save()
.then(function(SaveResponse response) {
let artistId: string = response.getModelId();
});