How to use Knex's 'with' method


#1

Hello, is there any way to use Knex’s with function in Lucid models?

It throws E_INVALID_MODEL_RELATION because Lucid has built-in with method for loading relationships

@virk


#2

In Lucid the with() method works to create an eagger loading relationship, what you show is a CTE Common Table Expression to avoid the subqueries usage.

What do you need exactly?


#3

For example, I want to get sum of like_count of every entry for challenges like the code block below (but as you and I mentioned, Lucid has own with method for loading relationships)

Challenges --hasMany--> Entries

const Challenge = use('App/Models/Challenge')


const challengeId = 5
const challenges = await Challenge
  .query()
  .with('entries')
  .withCount('entries')
  .with('total_like_count', builder => {
    builder.where({ challenge_id: challenge_id }).getSum('like_count')
  })


Fetch data and related foreign key related object