📅  最后修改于: 2023-12-03 15:29:18.264000             🧑  作者: Mango
Adonis Preload Recursive is a library for the AdonisJS framework that allows developers to easily preload nested relations for their models.
To install Adonis Preload Recursive, use the following command:
npm install @ioc:Adonis/Addons/Adonis-Preload-Recursive
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.
Adonis Preload Recursive takes the following options:
['comments', 'comments.author']
.const posts = await Post.query()
.preloadRecursive('comments', (query) => query.limit(3))
.orderBy('id', 'desc');
return response.json(posts);
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.