Skip to content

Creating and saving

DavidDuwaer edited this page Nov 23, 2017 · 9 revisions

Query building

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()

  1. If artist has an ID set (i.e. artist.getId() would not return null), then this would yield an HTTP PATCH query. If no Artist with the ID is found in the backend, this query would fail.
  2. If artist does not have an ID set, this query would yield an HTTP POST query, creating a new Artist in 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();

The response object

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();
    });
Clone this wiki locally