With
with
Method Documentation
The with
method allows loading related models or entities through eager loading. It supports specifying a single relation, multiple relations, and dynamic relations through type-safe arrays.
Note:
After finishing building your query attach .build()
to generate it.
Method Signature
with(relations: ExtractRelations<T> | ExtractRelations<T>[]): this;
Parameters
relations
:- A single relation name as a string, or
- An array of relation names.
Returns
The current instance, enabling method chaining.
Examples
Assuming the following typescript interfaces
interface User {
id: number;
name: string;
email: string;
posts: Post[];
comments: Comment[];
}
interface Post {
id: number;
title: string;
content: string;
author: User;
}
interface Comment {
id: number;
content: string;
commenter: User;
}
Starting the query
const query = createQuery<User>('/api/users') // mark the base url
query.with("posts");
// Posts is expected to be typesafe if the interface was assigned as a generic tot the createQuery function.
2. Multiple Relations (Array)
query.with(["posts", "comments"]);
// Posts and comments is expected to be typesafe if the interface was assigned as a generic tot the createQuery function.
3. Dynamic Relations (Type-Safe)
Assuming you have 2 interfaces like this
import ExtractRelations from 'queryBuilder'
const relations: ExtractRelations<Post>[] = ["author", "category"];
query.with(relations);
4. Nested Relations
import ExtractRelations from 'queryBuilder'
const relations: ExtractRelations<Post>[] = ["author.comments", "category"];
query.with(relations);
With Cases Table
Format | Example | Use Case |
---|---|---|
Single Relation | query.with("author") | Load one related model |
Nested Relation | query.with("author.comments") | Load one related model and it's related relation |
Multiple Relations | query.with(["author", "tags"]) | Load multiple models |
Dynamic Relations | query.with(relations) | Type-safe relation loading |