objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Writing a subquery for a relation's relation

Open armenavanesi opened this issue 4 years ago • 0 comments

I'm using version 2.2.15 at the moment and I'm following the relation subqueries recipe. I've outlined my models and their relationships towards the bottom.

Currently, I'm fetching an event as well as it's post count using this query:

const events = await Event.query().select([
  'events.*',
  Event.relatedQuery('posts')
    .count()
    .as('numberOfPosts'),
  ]);

Which works fine - but how can I include the count of each of the event's post's users, that is, the total amount of user's going to an event. I've tried using a ref like so without luck:

const events = await Event.query().select([
  'events.*',
  Event.relatedQuery('posts')
    .count()
    .as('numberOfPosts'),
  Post.query().where('eventId', ref('events.id')),
]);

Thank you 👋

Models and their relationships:

Event:

posts: {
  relation: Model.HasManyRelation,
  modelClass: Post,
  join: {
    from: 'events.id',
    to: 'posts.eventId',
  },
},

Post:

event: {
  relation: Model.BelongsToOneRelation,
  modelClass: Event,
  join: {
    from: 'posts.eventId',
    to: 'events.id',
  },
},
users: {
  relation: Model.ManyToManyRelation,
  modelClass: User,
  join: {
    from: 'posts.id',
    through: {
      // users_posts is the join table.
      from: 'users_posts.postId',
      to: 'users_posts.userId',
    },
    to: 'users.id',
  },
},

User:

posts: {
  relation: Model.ManyToManyRelation,
  modelClass: Post,
  join: {
    from: 'users.id',
    through: {
      // users_posts is the join table.
      from: 'users_posts.userId',
      to: 'users_posts.postId',
    },
    to: 'posts.id',
  },
},

armenavanesi avatar Jan 24 '22 08:01 armenavanesi