I found a solution and post here hoping it can help others.
First of all, I needed clean copies of the query to create subqueries without ending up in an infinite loop. There I removed all previous WHERE
conditions.
Then I called where()
to the original query using a callback method. This gave me the access to manipulate the QueryExpression
.
As I wanted to chain the custom finder queries with OR
condition I needed a starting condition, what always false, that is why I have 1 = 0
condition. Then I was able to use the QueryExpression
's add()
method to chain the queries.
$cleanQueryCorporate = $query->cleanCopy()
->select(['Accounts.id'])->where(null, [], true);
$cleanQueryCompany = $query->cleanCopy()
->select(['Accounts.id'])->where(null, [], true);
$query->where(function (QueryExpression $exp) use ($access, $cleanQueryCorporate, $cleanQueryCompany, $options) {
$exp = $exp->or('1 = 0'); // this needed to add the next ones with OR
if (isset($access->corporate)) {
$exp = $exp->add(['Accounts.id IN'=> $cleanQueryCorporate
->find('forCorporate', ['corporate_id' => $access->corporate])]);
}
if (isset($access->company)) {
$exp = $exp->add(['Accounts.id IN'=> $cleanQueryCompany
->find('forCompany', ['company_id' => $access->company])]);
}
return $exp;
});