Vincit / objection.js

An SQL-friendly ORM for Node.js
https://vincit.github.io/objection.js
MIT License
7.25k stars 636 forks source link

What is best way to write date based complex query in objection. #1066

Closed mayankparihar1988 closed 6 years ago

mayankparihar1988 commented 6 years ago

SELECT Max("currNumber") FROM "test"."Mytable" WHERE date_part('year',"createDate") = date_part('year',current_date);

I am looking following Postgresql query to convert in objection.

kibertoad commented 6 years ago

Objection doesn't provide any additional tools over what Knex.js already has for date manipulation, and even Knex is unlikely to help you with something that specific. I suspect that .whereRaw is your best bet here.

mayankparihar1988 commented 6 years ago

Is there any way to execute raw sql query through knex.

koskimas commented 6 years ago

A simple search through the docs should answer that question. But here you go

const  { raw } = require('objection')

...

await MyTable
  .query()
  .where(raw(`date_part('year', "createDate") = date_part('year', ?)`, current_date))
kibertoad commented 6 years ago

@koskimas Any meaningful difference between .where(raw()) and .whereRaw()?

mayankparihar1988 commented 6 years ago

Thanks a lot @koskimas I am very new to programming :) . Thanks for help.

koskimas commented 6 years ago

@kibertoad Nope. whereRaw comes from the knex API.