📜  adonis lucid join - Javascript (1)

📅  最后修改于: 2023-12-03 14:59:11.978000             🧑  作者: Mango

Adonis Lucid - JavaScript ORM

Introduction

Adonis Lucid is an Object Relational Mapping (ORM) package for JavaScript applications. It makes it easier for developers to work with databases by providing a straightforward way to interact with database models and perform CRUD operations. This package is specifically designed for the Adonis framework but can also be used as a standalone library.

Features
  • CRUD operations: Easily create, read, update, and delete records in the database.
  • Relationships: Define and manage relationships between models such as one-to-one, one-to-many, and many-to-many.
  • Query builder: Construct complex database queries using a fluent and chainable API.
  • Transactions: Perform database operations within a transaction to ensure data integrity.
  • Soft deletes: Soft delete records by marking them as "deleted" without permanently removing them from the database.
  • Serialization and Deserialization: Automatically convert model instances to plain objects and vice versa.
  • Hooks: Execute custom logic before or after certain model actions like creating, updating, or deleting records.
  • Eager loading: Load related models in a single query to optimize performance.
  • Scopes: Define reusable query scopes to easily filter and sort records.
Getting Started

To use Adonis Lucid in your JavaScript application, you need to install it first using npm or yarn:

npm install @adonisjs/lucid

Once installed, you can import it in your code:

const { BaseModel } = require('@adonisjs/lucid/orm');
Example Usage

Here's an example of how to define a simple User model and perform CRUD operations using Adonis Lucid:

const { BaseModel } = require('@adonisjs/lucid/orm');

class User extends BaseModel {
  static get table() {
    return 'users';
  }

  static scopeActive(query) {
    return query.where('active', true);
  }
}

// Create a new user
const user = new User();
user.username = 'john.doe';
user.email = 'john.doe@example.com';
await user.save();

// Find a user by ID
const foundUser = await User.find(1);

// Update a user
foundUser.email = 'john.doe2@example.com';
await foundUser.save();

// Delete a user
await foundUser.delete();

// Find all active users
const activeUsers = await User.query().active().fetch();

// Serialize a user to JSON
const jsonUser = user.toJSON();
Conclusion

Adonis Lucid provides a convenient and powerful way to interact with databases in JavaScript applications. With its comprehensive set of features, developers can easily model their data, perform database operations, and manage relationships. It offers a smooth development experience while maintaining data integrity and performance. Give it a try and see how it can simplify your backend development process!