admin管理员组

文章数量:1287246

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%'

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%'
Share Improve this question edited Dec 24, 2018 at 14:06 Billal BEGUERADJ 22.8k45 gold badges123 silver badges140 bronze badges asked May 25, 2017 at 16:48 ottosattoottosatto 6011 gold badge4 silver badges16 bronze badges 1
  • What is the point of using all those fancy ORM-s and to seek raw-query execution at the same time? – vitaly-t Commented May 25, 2017 at 17:21
Add a ment  | 

2 Answers 2

Reset to default 6

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+'%'})

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.

本文标签: javascriptAdonisjs search queriesStack Overflow