Lucid ORM
Lucid in Adonis.js is the official Object-Relational Mapper (ORM) built on top of Knex.js, designed to provide an active record-style data modeling and querying layer for SQL databases within Adonis.js applications.123
Core Features
- Lucid allows you to define models as JavaScript (or TypeScript) classes that map directly to your database tables. Each model extends a
BaseModeland defines columns using decorators, supporting both direct data mapping and custom business logic.21 - CRUD operations are streamlined, letting you create, read, update, and delete database records using intuitive class-based methods rather than raw SQL queries.32
- Relationships between models (e.g., hasOne, hasMany, belongsToMany) are easily managed, providing convenient methods for traversing and querying related data.43
- Lifecycle hooks, serialization control, and custom methods/properties allow you to encapsulate domain logic cleanly within each model.34
Supported Databases
- Works with PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server out-of-the-box, letting you choose or migrate across major SQL databases easily.5
Example Model (TypeScript)
import { DateTime } from 'luxon'
import { BaseModel, column } from '@adonisjs/lucid/orm'
export default class User extends BaseModel {
@column({ isPrimary: true })
declare id: number
@column.dateTime({ autoCreate: true })
declare createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
declare updatedAt: DateTime
}
Usage and Customization
- Models are typically located in the
app/Modelsdirectory. - You can leverage Lucid for advanced features like eager loading, query scopes, and pagination, as well as transactional operations.4
- Lucid integrates tightly with AdonisJS CLI tools for creating migrations, models, factories, and seeders to help manage and populate your database schema.5
Installation
To install Lucid in your AdonisJS project:
npm i @adonisjs/lucid
After installing, the setup process will help configure database connections and essential dependencies like Luxon for date handling.5
Lucid ORM is an integral and powerful part of the Adonis.js ecosystem, focusing on developer productivity, maintainability, and a rich Active Record pattern for database management.2135
-
https://adocasts.com/lessons/introducing-installing-and-configuring-lucid-orm ↩ ↩2 ↩3 ↩4
-
https://news.ycombinator.com/item?id=35256796 ↩
-
https://stackoverflow.com/questions/55077645/adonis-lucid-orm-not-returning-data ↩
-
https://www.youtube.com/watch?v=w4fMW8UJ310 ↩
-
https://github.com/francisjed/adonis-lucid ↩
-
https://adocasts.com/lessons/lets-learn-adonis-5-setting-up-lucid ↩