I have 3 tables:
clients
, clients_traders_relation
, traders
This is a many-many relation, clients can have many traders and traders can have many clients.
I have 2 relations in the clients
model:
'traderssearch' => array(self::MANY_MANY, 'traders', 'clients_traders_relation(relation_id, trader_id)'),
'traders' => array(self::MANY_MANY, 'traders', 'clients_traders_relation(relation_id, trader_id)'),
The traderssearch
relation is used for limiting access to clients that don't belong to the current trader (so traders see only their clients, or if they are one of the traders). The traders
relation is used for obtaining all the traders (this is a solution I got from my other question, because one relation would only return the current trader, even if there are more.
It's used in defaultScope like this:
return array(
'alias' => $class,
'with' => array(
'traderssearch' => array(
'together' => true,
'condition' => 'traderssearch.id='. Yii::app()->user->getId()),
'traders',
),
However, I'd like to have the ability to search for clients of some other trader. So let's say I have 3 clients:
- Client A, traders: me, XYZ
- Client B, traders: me
- Client C, traders: XYZ
I want to search for client's of XYZ. It should return only Client A, because that's the only client related both to me and XYZ.
I did it like this in search():
$criteria->with = 'traderssearch';
$criteria->together = true;
$criteria->compare('traderssearch.id', $this->search_trader);
search_trader
is an additional variable added to the model so it can be used for searching.
If I display a list of clients without using search, it works okay. But if I try to search for client's of XYZ, it returns me nothing. i think that is because both of these conditions are excluding themselves, something like id = 10 AND id = 20
which will never be true.
I tried adding an OR
to compare()
but it didn't work.
If I remove the condition from defaultScope, searching works because now there's only one condition searching for trader id. Is there any way to keep both the defaultScope and search conditions? Would I need another, third relation?