Creating a lucid model in AdonisJs

Here, we are going to learn about the lucid model, how to create a create a lucid model in AdonisJs?
Submitted by Radib Kar, on January 17, 2021

In the last tutorial, we detailed about introduction to lucid models and also learned about the default model that got created in the boilerplate. We also updated the user model to add function projects(). In this tutorial, we will be creating a lucid model from scratch for projects & tasks.

Command to creating a lucid model

To create a model we have an adonis command which is like below:

adonis make:model <Model name>

The general convention of the model name is to keep the first letter at Caps and name to be in the singular. Like for users table, the model name will be "User" as per convention. Similarly, for projects table, the model name will be "Project" as per convention. So to create the model for projects table, we need to hit,

adonis make: model Project

This should create the model like below:

AdonisJs | Lucid Model (1)

AdonisJs | Lucid Model (2)

Similarly, create the model for Tasks.

Now, as we added relationship in the user model, in the project & task model also we need to add relationships. 

Example

For example:

The project will belong to a user & the project will consist of many tasks. So the relationship b/w user & project will be "belongsTo" from project perspective. Similarly, the relationship b/w tasks & project will be "hasMany" from project perspective.

user(){
    return this.belongsTo('App/Models/User');
}
tasks () {
    return this.hasMany('App/Models/Task')
}

This will create the project model. Now, I would recommend you to create the task model provided a task will belong to a project.

Below is the final model details.

Project model:

AdonisJs | Lucid Model (3)

Task model:

AdonisJs | Lucid Model (4)

Comments and Discussions!

Load comments ↻





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