Confusing whereHas functionality
shahar-mintz opened this issue · 0 comments
Hey, I've been using adonis-lucid-polymorphic on a new project and just encountered a confusing issues. Briefly, the MorphTo's whereHas
query (seems like also true for has
query) only considers the first model in the relatedModels
array, resulting in incomplete results.
Example:
Model Setup
class Video extends Model {
}
class Post extends Model {
}
class Comment extends Model {
static get traits () {
return ['@provider:Morphable']
}
commentable () {
return this.morphTo([
Video,
Post
], 'id', 'id', 'commentable_id', 'commentable_type')
}
}
When I run this code
let _query = null;
Comment.onQuery((query) => (_query = query));
await Comment.query().whereHas('commentable', b=>b.where('id', '>', 2)).fetch();
The resulting SQL query (_query.sql
) is
'select * from "comments" where exists (select * from "videos" where "id" > ? and "comments"."commentable_id" = "videos"."id")'
The problem
The query should return all the comments for the commentables with id>2. Instead, it considers only the Video
model and neglects the Post
model. So for example, if I had no videos but only 10 posts (ids 1-10), the query would return zero results which isn't correct (should have returned 8 posts, with ids 3-10).
Thanks for your help.