0

I'm building a node js app with Objection + knex. I was wondering if that is possible to access the declared property in the Model when doing the request ? That way, TS is everywhere. In the doc, every time the Model property are inside string.

Here is my model

export class AgencyModel extends BaseModel {
    static tableName = 'agency'
    readonly id!: number
    agency_name!: string
}

Here is the way im requesting it for eg

return AgencyModel.query()
            .modify((queryBuilder) => {
                if(agencyParameters.search) {
                    const searchFilter = (agencyParameters.search).toLowerCase()
                    queryBuilder.where('agency_name', 'ILike', `%${searchFilter}%`)
                }
            })
            .paginate(agencyParameters.getLimit(), agencyParameters.getOffset())

But we can see that I have to write 'agency_name' in string. I would like to be able to do something like this

queryBuilder.where(AgencyModel.agency_name, 'ILike', `%${searchFilter}%`)

Is there a way I can achieve this ? That way, the day made a change in my DB, one column name, I can update the model and all the code will follow + i have typescript to avoid make mistake inside my requests.

Thanks for reading.

Unreality
  • 4,111
  • 11
  • 48
  • 67
TPCRomain
  • 51
  • 2

1 Answers1

0

you can certainly do this by defining a static attribute

static agency_name = 'agency_name'

and then call it using

AgencyModel.agency_name

however i'm not sure if this affects anything on the model level so you can group it under a new object

static columns = {
    agency_name: 'agency_name',
    created_at: 'created_at',
    updated_at: 'updated_at',
}

and then call it using

AgencyModel.columns.agency_name
M-Raw
  • 779
  • 4
  • 10
  • Using static is impossible, but i guess doing a columns object is the best way to achieve it ! Thanks :) – TPCRomain May 28 '22 at 09:17