Dung (Donny) Nguyen

Senior Software Engineer

Search for Records with Lucid ORM

In Adonis.js, using Lucid ORM to search for a record is super intuitive. Here are a few common ways to do it:

๐Ÿ” Basic Lookups

๐Ÿง  Using Query Builder

For more complex queries:

const user = await User.query()
  .where('username', 'dungdev')
  .andWhere('is_active', true)
  .first()

You can also use firstOrFail() or findOrFail() if you want it to throw an error when no record is found.

๐Ÿ’ก Bonus: Partial Match (LIKE)

const users = await User.query()
  .where('email', 'like', '%@gmail.com')
  .fetch()

Lucid ORM packs some serious power under the hood beyond the usual CRUD and relationship handling. Here are some additional advanced features that can really elevate your Adonis.js projects:


๐Ÿง  SQL Superpowers

Lucid is built on top of Knex, so it supports:


๐Ÿงฐ Read/Write Replicas

You can configure read-write splitting to scale your app:

{
  connection: 'mysql',
  replicas: {
    write: { host: 'write-db' },
    read: [{ host: 'read-db-1' }, { host: 'read-db-2' }]
  }
}

Lucid will automatically route queries to the appropriate replica.


๐Ÿงช Model Factories & Seeders

Generate fake data for testing or development:

const user = await Factory.model('App/Models/User').create()

Perfect for simulating real-world scenarios or populating dev environments.


๐Ÿช Lifecycle Hooks

Tap into model events like beforeCreate, afterSave, etc.:

@beforeSave()
public static async hashPassword(user: User) {
  if (user.$dirty.password) {
    user.password = await Hash.make(user.password)
  }
}

๐Ÿงฉ Custom Serialization

Control how models are converted to JSON:

public serializeExtras = true
public serializeComputed = true

You can also define computed properties and hide sensitive fields.


๐Ÿงฌ Multiple Connections

Need to connect to more than one database? Lucid supports multiple named connections, so you can query across different DBs in the same app.


You can also check out the Lucid documentation for a deeper dive.