Home »
AdonisJs
AdonisJs | Lucid Query Builders | Part 2
Here, we are going to learn about the lucid query builders which will help us insert or update rows in the database.
Submitted by Radib Kar, on February 13, 2021
Prerequisite
AdonisJs | Lucid Query Builders | Part 1
In our last tutorial, we discussed how the query builder helps to skip writing SQL queries manually? And, a few examples of query builders. I also shared the doc link where you can find more query builders.
In this article, we will focus on query builders which will help us insert or update rows in the database. This is most frequent using query builders for PUT, PATCH requests.
create()
Creates a new instance of the model.
Example
Below is an example to insert a new row in a project table where Project is the model imported and say we have already grabbed the input fields from the request body (shown in our last tutorial).
const Project = use('App/Models/Project');
//say we already have grabbed title & descriptions from the request body
const project = new Project();
project.fill({
title,
description
});
await Project.create(project);
save()
Saves an instance. If the instance is there already it updates that instance otherwise creates a new one.
Example
Below is the same example as the above one. But instead of using we have used the save() method.
const project = new Project();
project.fill({
title,
description,
});
await Project.save(project);
Similarly we have update(), delete(), attach() methods which you can see the usages here (Inserts, Updates & Deletes).