Lucid: use where inside of with

Created on 27 Mar 2018  路  3Comments  路  Source: adonisjs/lucid

I have a Model and I want to use where inside it.
for example I have a User Model and Post Model and I want to use this query

.query()
.with("user")
.where("user.username","like","%john%")

and my result must be All post that owner username is john

Most helpful comment

That's wrong sorry, I think you'll need whereHas

const posts = await Post
  .query()
  .whereHas('user', (builder) => {
    builder.where('username', 'like', '%john%')
  })
  .fetch()

All 3 comments

See Adding Runtime Constraints

const posts = await Post
  .query()
  .with('user', (builder) => {
    builder.where('username', 'like', '%john%')
  })
  .fetch()

That's wrong sorry, I think you'll need whereHas

const posts = await Post
  .query()
  .whereHas('user', (builder) => {
    builder.where('username', 'like', '%john%')
  })
  .fetch()

tnx @webdevian for your answer.
know how can orderBy whit username in the same example.

Was this page helpful?
0 / 5 - 0 ratings