Cannot use joins with composite expressions
| Q | A |
|---|---|
| Version | 4.3.4/3.10.1 |
Summary
Doctrine\DBAL\Query\Join class does not support CompositeExpression.
Current behavior
When having code similar to:
$query->innerJoin(
'r',
'rule',
'rt',
$query->expr()->and(
$query->expr()->eq('r.id', 'rt.rule_id'),
$query->expr()->eq('r.status', 'rt.status'),
),
)
I'm getting the error Doctrine\DBAL\Query\QueryBuilder::innerJoin(): Argument #4 ($condition) must be of type ?string, Doctrine\DBAL\Query\Expression\CompositeExpression given
It seems that join/innerJoin/leftJoin/rightJoin methods do not support CompositeExpression class. Is there are reason for that behaviour?
Expected behavior
I expect this snippet to work fine. It works in 3.10.x because there are no typehints, but PHPStan emits an error nevertheless due to PHPDoc types.
How to reproduce
Just use a join with a condition expression that returns a CompositeExpression like and().
Is there are reason for that behaviour?
I'm not aware of any decision to deliberately not support composite expressions. In https://github.com/doctrine/dbal/pull/3841, the parameter types for join methods were added based on phpDocs, which only allowed using strings.
We can widen the types and allow composite expressions, but it will be a BC break since QueryBuilder is not final.
To avoid a BC break, would it be possible to fix this by removing the typehints as it was in 3.x, and then in 5.x re-add them with correct types, or is it too much of a hassle?
Or to change ExpressionBuilder::and and ExpressionBuilder::or to return string instead of CompositeExpression, since the issue boils down to these two methods not returning strings like other methods in ExpressionBuilder class.
What I'm really interested in is how this hasn't popped up anywhere before? I mean, my snippet above is not something out of the ordinary, right?
Or to change
ExpressionBuilder::andandExpressionBuilder::orto returnstringinstead ofCompositeExpression, since the issue boils down to these two methods not returning strings like other methods inExpressionBuilderclass.
CompositeExpression has __toString() method. You can cast the expression to a string.
I know I can, this is my fallback option, yes, but I believe this should be solved in DBAL itself, as it is an integral part of it, being able to use expression builder without friction in joins.