SERIES
AdonisJS Quick Tip
-
1.0Getting Data by the User's Timezone with Luxon's DateTime05:544:32
-
2.0Debugging, Inspecting, and Freezing Code Execution11:163:36
-
3.0How To Add AdonisJS Edge Support to your WebStorm Environment01:521:18
-
4.0How To Add TailwindCSS to a New AdonisJS Project04:485:14
-
5.0How To Serialize All AdonisJS Lucid Model Properties As Camel Case06:234:55
-
6.0How To Add A Global Property To Your HttpContext in AdonisJS 508:528:37
-
7.0How To Add A Custom Method to the Model Query Builder in AdonisJS09:504:31
-
8.0How To Make Your AdonisJS Authentication Login Case-Insensitive06:003:21
-
9.0Http Method Spoofing & Helper Components in AdonisJS09:174:29
-
10.0How To Use Vue 3 with TypeScript in an AdonisJS Project10:136:55
-
11.0How To Create Your Own Global Helpers in AdonisJS08:189:43
-
12.0Minify Your AdonisJS HTML in 5 Minutes06:231:03
-
13.0How To Redirect Back to the Previous Page After Login with AdonisJS03:043:41
-
14.0Remember Me in AdonisJS Authentication04:130:26
-
15.0How To Seamlessly Share AdonisJS Sessions & Authentication Across Subdomains04:230:12
-
16.0Exploring My Favorite AdonisJS Model Query Builder Macros: Tips and Examples09:241:59
AdonisJS Quick Tip
Exploring My Favorite AdonisJS Model Query Builder Macros: Tips and Examples
09:24 Watch
1:59 Read
In this lesson, I'll highlight a few of my favorite Model Query Builder Macros that I carry with me from project to project. Have a favorite of your own? Let me know in the comments!
🕑 Chapters
- Macro WhereTrue & WhereFalse
- Macro Any
- Macro SelectCount
- Macro SelectIds
- Macro SelectId
- Macro SelectIdOrFail
- Macro Outro
Model Query Builder Macro Provider
import type { ApplicationContract } from '@ioc:Adonis/Core/Application'
/*
|--------------------------------------------------------------------------
| Provider
|--------------------------------------------------------------------------
|
| Your application is not ready when this file is loaded by the framework.
| Hence, the top level imports relying on the IoC container will not work.
| You must import them inside the life-cycle methods defined inside
| the provider class.
|
| @example:
|
| public async ready () {
| const Database = this.app.container.resolveBinding('Adonis/Lucid/Database')
| const Event = this.app.container.resolveBinding('Adonis/Core/Event')
| Event.on('db:query', Database.prettyPrint)
| }
|
*/
export default class ModelQueryBuilderMacroProvider {
constructor(protected app: ApplicationContract) {}
public register() {
// Register your own bindings
}
public async boot() {
// All bindings are ready, feel free to use them
const { ModelQueryBuilder } = this.app.container.resolveBinding('Adonis/Lucid/Database')
// adds truthy where statement check on the query builder
ModelQueryBuilder.macro('whereTrue', function(columnName: string) {
return this.where(columnName, true)
})
// adds falsy where statement check on the query builder
ModelQueryBuilder.macro('whereFalse', function(columnName: string) {
return this.where(columnName, false)
})
// returns whether any records mached the built query
ModelQueryBuilder.macro('any', async function() {
const result = await this.count('* as total')
return result.at(0).$extras.total > 0
})
// returns just the final count result for the query
ModelQueryBuilder.macro('selectCount', async function() {
const result = await this.count('* as total')
return BigInt(result.at(0).$extras.total)
})
// returns an array of ids for the built query
ModelQueryBuilder.macro('selectIds', async function(primaryKey: string = 'id') {
const results = await this.select(primaryKey)
return results.map(result => result[primaryKey])
})
// returns the first id for the built query
ModelQueryBuilder.macro('selectId', async function(primaryKey: string = 'id') {
const result = await this.select(primaryKey).first()
return result && result[primaryKey]
})
// returns the first id for the built query, throws if no records
ModelQueryBuilder.macro('selectIdOrFail', async function(primaryKey: string = 'id') {
const result = await this.select(primaryKey).firstOrFail()
return result[primaryKey]
})
}
public async ready() {
// App is ready
}
public async shutdown() {
// Cleanup, since app is going down
}
}
Model Query Builder Macro Context
declare module '@ioc:Adonis/Lucid/Orm' {
interface ModelQueryBuilderContract<
Model extends LucidModel,
Result = InstanceType<Model>
> {
// macro typescript definitions here
whereTrue(columnName: string): this
whereFalse(columnName: string): this
any(): Promise<boolean>
selectCount(): Promise<BigInt>
selectIds(primaryKey?: string): Promise<number[]>
selectId(primaryKey?: string): Promise<number | undefined>
selectIdOrFail(primaryKey?: string): Promise<number>
}
}
Comment
Prepared By
Tom Gobich
Burlington, KY
Owner of Adocasts, JavaScript developer, educator, PlayStation gamer, burrito eater.
Visit Website