How to make macro from ModelQueryBuilder Lucid ORM #4592
Unanswered
adityadarma
asked this question in
Help
Replies: 1 comment 1 reply
-
I did this, but don't know if is the best way:
import { ModelQueryBuilder } from '@adonisjs/lucid/orm'
declare module '@adonisjs/lucid/types/model' {
interface ModelQueryBuilderContract<Model, Result> {
whereTrue(column: string): this
whereFalse(column: string): this
value<T>(column: string): Promise<T | undefined>
values<T extends Record<string, any>>(): Promise<T | undefined>
getCount(): Promise<number>
}
}
declare module '@adonisjs/lucid/orm' {
interface ModelQueryBuilder {
whereTrue(column: string): this
whereFalse(column: string): this
value<T>(column: string): Promise<T | undefined>
values<T extends Record<string, any>>(): Promise<T | undefined>
getCount(): Promise<number>
}
}
ModelQueryBuilder.macro('whereTrue', function (this: ModelQueryBuilder, column: string) {
return this.where(column, true)
})
ModelQueryBuilder.macro('whereFalse', function (this: ModelQueryBuilder, column: string) {
return this.where(column, false)
})
ModelQueryBuilder.macro('getCount', async function (this: ModelQueryBuilder) {
return this.count('* as total')
.first()
.then((res: any) => res.$extras.total)
})
ModelQueryBuilder.macro('value', async function (this: ModelQueryBuilder, column: string) {
return this.limit(1)
.pojo()
.then((rows: any[]) => rows[0][column])
})
ModelQueryBuilder.macro('values', async function (this: ModelQueryBuilder) {
return this.limit(1)
.pojo()
.then((rows: any[]) => rows[0])
}) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I was confused when I wanted to add macros to the Lucil model, because there was an additional global scope
please help me
Beta Was this translation helpful? Give feedback.
All reactions