I have this SQL query that is doing what I want:
1 2 3 4 |
|
I tried copying it as a Yii query builder like this:
1 2 3 4 5 6 7 8 9 |
|
But I printed the SQL generated by this query builder using getRawSql()
and it returned this weird way:
1 2 3 4 5 6 7 8 9 10 11 |
|
Sorry if this is hard to read.
Can anyone help me make the query builder the way I want? I will be very grateful
P粉5961919632024-04-02 19:22:21
Whenever you use andWhere()
or orWhere()
, the query builder takes the existing conditions and does something like this:
or
respectively.
So if you have faced some complex situation then try calling
1 2 |
|
You will get
But in your case you need to get something like:
To achieve similar results, you can construct the first complex condition in the same way, but the second condition must be constructed in a single orWhere()
call. Or to make it more readable, you can build two complex conditions separately in a single call:
Table1::find()
->joinWith(['table2'])
->where([
'AND',
['Table1.idOwner' => $idOwner, 'Table2.enabled' => 1],
['<=', 'day(Table2.creationDate)', $expirationDay],
['=', "date_format(Table2.creationDate, '%Y-%m')", $previousExpirationMonthYear]
])->orWhere([
'AND',
['Table1.idOwner' => $idOwner, 'Table2.enabled' => 1],
['!=', "date_format(Table2.creationDate, '%Y-%m')", $currentExpirationMonthYear],
['!=', "date_format(Table2.creationDate, '%Y-%m')", $previousExpirationMonthYear]
])->all();