HAS_MANY AR relation on multiple columns


I have 2 tables: Person and Transaction.

Transaction has 2 columns: personFrom_id and personTo_id referring to Person.id

A person can appear in multiple transactions as either from or to.

I would like to have an AR relation to list out all transactions a person has participated in (both from and to)

This doesn’t seem to work (in model/Person.php)

	public function relations()


		'transactions' => array(self::HAS_MANY,'	

			'condition'=>'`transaction`.`personFrom_id` = `t`.`id` OR `agreements`.`personTo_id` = `t`.`id`',




Nor does this

	public function relations()


		'transactions' => array(self::HAS_MANY,'	

			'condition'=>'`transaction`.`personFrom_id` = :id OR `agreements`.`personTo_id` = :id',





I also tried ‘on’ instead of ‘condition’

Creating 2 separate AR relations transactions_from and transactions_to works, obviously - but I would prefer to avoid that…

Does anyone have a suggestion ?

Thanks !

That won’t work because relations require you to pass in 3 parameters (relation type/class, AR class, FK), then it builds out the necessary criteria and joins for you. I guess you keep both from and to relations and just create a method inside your model that would use those 2 and bring back an array with all the data you need.

declare a method on your person model like so it give you more control over conditions

public function getTransactions()


        $criteria = new CDbCriteria;

        $criteria->condition = '`transaction`.`personFrom_id` = :id OR `agreements`.`personTo_id` = :id';

        $criteria->params = [':id' => $this->primaryKey];

        return Transaction::model()->findAll($criteria);


// you are still able to do


// Note: double check your relation ids

thank you both for your constructive replies :)

Pity there doesn’t seem to be a way to get this through a relation - but I guess having a method is the next best thing…


Please use this relation in person model.

‘transactions’=>array(self::HAS_MANY, ‘transaction’, ‘id’,‘condition’=>’transaction.personFrom_id = t.id OR transaction.personTo_id = t.id’),

Hi Anamika,

Unfortunately that doesn’t work. It still gives the dreaded

Column not found: 1054 Unknown column 't.id' in 'where clause'

error :unsure:

Hi Coriolan,

Please use this relation. This is working fine,because i have tested on my code.

‘transactions’=>array(self::HAS_MANY, ‘transaction’, ‘’,‘on’=>’transaction.personFrom_id = t.id OR transaction.personTo_id = t.id’),

If you have any issue please share your model files of both table.