3

I'm trying to find a way to execute a search query using AdonisJs but I cannot find any way to do this with Lucid ORM...

I'm currently using this, but it's clearly not the right way to make a search query:

let posts = yield Post.query().with('category').where({
   title: request.input('term')
}).forPage(1, 10).fetch()

How can I directly execute postgres SQL queries using adonis.js framework?

SELECT id FROM posts WHERE content LIKE '%searchterm%' OR WHERE tags LIKE '%searchterm%' OR WHERE title LIKE '%searchterm%'
Billal Begueradj
  • 13,551
  • 37
  • 84
  • 109
hailton
  • 457
  • 3
  • 12

2 Answers2

4

Found the solution to directly execute SQL queries in Adonis with Database.schema.raw(execute queries here), so:

const postQuery = yield Database.schema.raw('SELECT * FROM posts');
const posts = postQuery.rows
console.log(posts);

Edit 1
To perform a search query with Lucid ORM:

const term = request.input('term');
yield Database.select('*').from('posts').where('title', 'LIKE', '%'+term+'%')
console.log(posts);

Edit 2
Even better raw query:

yield Database.select('*').from('posts').whereRaw('title @@ :term OR description @@ :term', {term: '%'+term+'%'})
hailton
  • 457
  • 3
  • 12
2

Assuming you have a Model named Post.You can use the following query.

const term = request.input('term');
const posts = await Post.query().where('title', 'LIKE', '%'+term+'%').fetch()
console.log(posts);

If you want to select all attributes,you don't need to use select() Hope it will help you.

Sakil
  • 725
  • 1
  • 7
  • 17