📜  adonis preload recursive - TypeScript (1)

📅  最后修改于: 2023-12-03 15:29:18.264000             🧑  作者: Mango

Adonis Preload Recursive - TypeScript

Adonis Preload Recursive is a library for the AdonisJS framework that allows developers to easily preload nested relations for their models.

Installation

To install Adonis Preload Recursive, use the following command:

npm install @ioc:Adonis/Addons/Adonis-Preload-Recursive
Usage

To use Adonis Preload Recursive, first define your model with nested relations:

import { BaseModel, column, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm';

export class Post extends BaseModel {
  @column({ isPrimary: true })
  public id: number;

  @column()
  public title: string;

  @hasMany(() => Comment)
  public comments: HasMany<typeof Comment>;
}

export class Comment extends BaseModel {
  @column({ isPrimary: true })
  public id: number;

  @column()
  public body: string;

  @column()
  public postId: number;
}

Once your model is defined, you can call preloadRecursive to eagerly load nested relations:

const posts = await Post.query()
  .preloadRecursive('comments')
  .orderBy('id', 'desc');

return response.json(posts);

This will return an array of posts, each with its nested comments loaded.

Options

Adonis Preload Recursive takes the following options:

  • paths: an array of dot-separated paths to the nested relations to preload. For example, to preload both comments and their nested author relation, use ['comments', 'comments.author'].
  • queryCallback: a function that is called with each nested relation's query builder instance, allowing you to customize the query as needed. For example, you might want to limit the number of comments loaded:
const posts = await Post.query()
  .preloadRecursive('comments', (query) => query.limit(3))
  .orderBy('id', 'desc');

return response.json(posts);
Conclusion

Adonis Preload Recursive is a powerful library for AdonisJS developers who need to eagerly load nested relations. By allowing you to easily specify and customize the nested relations you need, it can help streamline your code and make your application more performant.