Skip to content

Fix BelongsToMany where_has with a query callback - #319

Merged
tmgbedu merged 2 commits into
mainfrom
fix/belongs-to-many-where-has-callback
Oct 27, 2026
Merged

tmgbedu merged 2 commits into
mainfrom
fix/belongs-to-many-where-has-callback

Conversation

@claude-tmgbedu

Copy link
Copy Markdown

Problem

BelongsToMany.query_where_exists called where_in(other_owner_key, callback(query.select(...))). With a normal callback such as lambda q: q.where("name", "Widget") the callback returns a QueryBuilder, which where_in tries to iterate, so Model.where_has("products", cb) / or_where_has raised TypeError: 'QueryBuilder' object is not iterable.

Fix

  • New related_exists_query(builder) builds the related-table query joined through the pivot and correlated to the parent; query_has and query_where_exists share it.
  • query_where_exists applies the callback to that related query inside the EXISTS (same as HasMany/BelongsTo). Callbacks that mutate in place and return None work too.
  • Callbacks that return an id list (the only form that worked before) still constrain related.other_owner_key with where_in.

No ADR (bug fix).

Tests

tests/masoniteorm/sqlite/relationships/test_belongs_to_many.py::TestBelongsToManyWhereHas covers where_has with no callback, a builder callback, a callback matching nothing, a callback returning None, an id-list callback, and or_where_has with and without a callback.

get_with_count_query has the same where_in(callback(...)) pattern but nothing in the builder calls it (there is no with_count), so it is left as is.

🤖 Generated with Claude Code

query_where_exists passed the callback's QueryBuilder to where_in, so
where_has/or_where_has with q.where(...) raised TypeError. Apply the
callback to the related EXISTS query joined through the pivot, keeping
id-list callbacks as a where_in on the related key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tmgbedu
tmgbedu merged commit a680446 into main Oct 27, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants