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.

1) create()

Creates a new instance of the model.

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

2) save()

Saves an instance. If the instance is there already it updates that instance otherwise creates a new one.

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




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.