$customers = Customer::find()->joinWith([
'orders' => function ($query) {
$query->onCondition(['customer.somevar' => 'someWord']);
},
])->all();
SELECT * FROM customer LEFT JOIN orders ON (customer.id=order.customer_id)
AND (customer.somevar='someWord')
SELECT * FROM order WHERE (id IN (1, 2, 3))
md5-8f1decc97fd3086d9471c80a050dafe7
```sql
SELECT * FROM order WHERE (id IN (1, 2, 3)) AND (customer.somevar='someWord')
| Q | A
| ---------------- | ---
| Yii version | 2.0.13
| PHP version | 7.0.20-2
| Operating system | Ubuntu 16.04.1
Why are you referencing the parent table in the join?
Can't you do
$customers = Customer::find()->joinWith([
'orders' => function ($query) { },
])->where(['customer.somevar' => 'someWord')->all();
Cause the full query was like this one:
$customers = Customer::find()->joinWith([
'orders' => function ($query) {
$query->onCondition(['customer.somevar' => 'someWord']);
},
'album.photos' => function ($query) {
$query->onCondition(['customer.somevar' => 'anotherWord']);
},
])->where(['customer.manyotherfilters' => 'fooBar'])->all();
I'm with you now, I'd encountered a similar issue a while back.
The solution I came up with was to check the primaryModel value of the join $query var.
$customers = Customer::find()->joinWith([
'orders' => function ($query) {
if ($query->primaryModel !== null) {
$query->onCondition(['customer.somevar' => 'someWord']);
}
},
'album.photos' => function ($query) {
if ($query->primaryModel !== null) {
$query->onCondition(['customer.somevar' => 'anotherWord']);
}
},
])->where(['customer.manyotherfilters' => 'fooBar'])->all();
This includes the extra onCondition when used as part of the join but ignores it when it's a SELECT.
onCondition is meant to be applied to both, the JOIN and the WHERE of a relational query. If you want to add additional condition to the JOIN only, you need to specify it outside as shown in https://github.com/yiisoft/yii2/issues/14387#issuecomment-312885987
so the solution is workaround
https://github.com/yiisoft/yii2/issues/14387#issuecomment-313031131
Most helpful comment
I'm with you now, I'd encountered a similar issue a while back.
The solution I came up with was to check the
primaryModelvalue of the join$queryvar.This includes the extra
onConditionwhen used as part of the join but ignores it when it's aSELECT.