Reputation: 1451
I should build up an sql query from a dynamically built up form. The user will select table fileds and AND/OR logical conditions between them. So in the end I should have an SQL query like this:
WHERE (
name LIKE "%foo%"
OR name LIKE "%bar%"
)
AND (
ad = "BP"
OR ad = "SV"
)
I tried
$query
->where(['Contacts.name LIKE' => '%foo%'])
->orWhere(['Contacts.cname LIKE' => '%bar%'])
->andWhere(function($exp){
return $exp->or_(
['Contacts.ad' => 'BP'],
['Contacts.ad' => 'SV']
);
})
);
What is clearly not good as I override Contacts.ad. I tried different ways but I was unable to get the right parenthesis.
The actual problem is more complex, as it may contain more fileds, not just this two (name and ad)
Upvotes: 0
Views: 1384
Reputation: 710
I would do this:
$query->where(['Contacts.name LIKE' => '%foo%'])
->orWhere(['Contacts.cname LIKE' => '%bar%'])
->andWhere([
'OR' => [
['Contacts.ad' => 'BP'],
['Contacts.ad' => 'SV']
]
]);
Upvotes: 1