AdonisJS Lucid核心功能解析:查询构建器与Active Record实战

【免费下载链接】lucid AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more 【免费下载链接】lucid 项目地址: https://gitcode.com/gh_mirrors/luc/lucid

AdonisJS Lucid是一个功能强大的SQL ORM,支持PostgreSQL、MySQL、SQLite等多种数据库,通过直观的API简化数据库操作。本文将深入解析其两大核心功能——查询构建器与Active Record模式,帮助开发者快速掌握这一高效工具。

什么是AdonisJS Lucid?

Lucid作为AdonisJS框架的官方ORM,采用Active Record设计模式,将数据库表映射为模型类,让开发者可以用面向对象的方式操作数据库。其核心优势在于:

  • 链式查询构建器:通过直观的链式调用构建复杂SQL查询
  • Active Record实现:模型实例直接映射数据库记录,支持CRUD操作
  • 多数据库支持:兼容主流关系型数据库
  • 迁移系统:版本化管理数据库结构变更

Lucid查询构建器:优雅构建数据库查询

Lucid的查询构建器提供了类型安全的API,让开发者无需编写原始SQL即可构建复杂查询。核心实现位于src/database/query_builder/目录,主要包括:

基础查询操作

查询构建器支持所有常见的SQL操作,通过链式调用组合条件:

// 基础查询示例
const users = await Database
  .from('users')
  .where('age', '>', 18)
  .andWhere('is_active', true)
  .orderBy('created_at', 'desc')
  .limit(10)

核心查询构建器类DatabaseQueryBuilder(定义于src/database/query_builder/database.ts)提供了完整的查询能力,包括selectwherejoingroupBy等方法。

关系查询构建器

Lucid为不同关系类型提供了专用查询构建器,如:

  • HasManyQueryBuildersrc/orm/relations/has_many/query_builder.ts):处理一对多关系
  • BelongsToQueryBuildersrc/orm/relations/belongs_to/query_builder.ts):处理多对一关系
  • ManyToManyQueryBuildersrc/orm/relations/many_to_many/query_builder.ts):处理多对多关系

这些构建器让关联数据查询变得简单:

// 获取用户及其所有帖子
const user = await User.find(1)
const posts = await user.related('posts').query().where('status', 'published')

Active Record模式:模型与数据库记录的无缝映射

Lucid的Active Record实现让每个模型实例对应数据库中的一条记录,所有CRUD操作都通过模型实例完成。

定义模型

所有模型都继承自BaseModelsrc/orm/base_model/index.ts),通过装饰器定义表结构:

import { BaseModel, column } from '@adonisjs/lucid/orm'

export default class User extends BaseModel {
  @column({ isPrimary: true })
  declare id: number

  @column()
  declare username: string

  @column()
  declare email: string
}

基本CRUD操作

Active Record模式让数据库操作直观易懂:

// 创建记录
const user = new User()
user.username = 'john_doe'
user.email = 'john@example.com'
await user.save()

// 查询记录
const user = await User.find(1)

// 更新记录
user!.email = 'new_email@example.com'
await user!.save()

// 删除记录
await user!.delete()

模型关系定义

Lucid支持多种关系类型,通过简单的方法定义:

import { hasMany, belongsTo } from '@adonisjs/lucid/orm'
import Post from './Post'
import Profile from './Profile'

export default class User extends BaseModel {
  @hasMany(() => Post)
  declare posts: HasMany<typeof Post>

  @hasOne(() => Profile)
  declare profile: HasOne<typeof Profile>
}

实战应用:构建完整的数据访问层

1. 安装与配置

首先通过Adonis CLI创建模型:

node ace make:model User

该命令会在app/models/目录下生成模型文件,并可选择生成迁移文件。

2. 高级查询示例

结合查询构建器和Active Record实现复杂查询:

// 获取活跃用户及其最新发布的帖子
const activeUsers = await User.query()
  .where('is_active', true)
  .preload('posts', (postsQuery) => {
    postsQuery
      .where('published_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .orderBy('published_at', 'desc')
      .limit(1)
  })
  .orderBy('last_login', 'desc')
  .limit(20)

3. 事务处理

Lucid提供简单的事务API,确保数据一致性:

import Database from '@ioc:Adonis/Lucid/Database'

const trx = await Database.transaction()

try {
  const user = new User()
  user.username = 'jane_doe'
  user.useTransaction(trx)
  await user.save()

  const profile = new Profile()
  profile.userId = user.id
  profile.useTransaction(trx)
  await profile.save()

  await trx.commit()
} catch (error) {
  await trx.rollback()
  throw error
}

总结

AdonisJS Lucid通过查询构建器和Active Record模式,大幅简化了数据库操作。其类型安全的API和丰富的功能,让开发者能够高效地构建数据访问层。无论是简单的CRUD操作还是复杂的关联查询,Lucid都能提供优雅的解决方案。

通过src/orm/query_builder/src/database/query_builder/等核心模块的精心设计,Lucid实现了强大而直观的数据库交互方式,是AdonisJS生态中不可或缺的重要组件。

【免费下载链接】lucid AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more 【免费下载链接】lucid 项目地址: https://gitcode.com/gh_mirrors/luc/lucid

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐