Automatic table name disambiguation in CActiveRecord relations

In my opinion, some form of mechanism for automatically disambiguating table names in CActiveRecord relations would be highly beneficial.

To give an example, I have a [i]text[/i] table and a [i]translation[/i] table for multilingual content. The [i]text[/i] table is simply an [i]id[/i] and [i]content[/i], and the [i]translation[/i] table contains the [i]text_id[/i] referring to the [i]text[/i] table that it is translating, a language [i]code[/i] that indicates the language of the translation, and [i]content[/i].

text table:






translation table:








So the primary key of the translation table is in fact a composite key made up of [i]text_id[/i] and [i]code[/i].

In our ‘Text’ (CActiveRecord) model, we therefore add the relation:

[i]‘translation’ => array(self::HAS_ONE,



'on' => '`language_code` = :language',

'params' => array(

	':language' => Yii::app()->language



in order to give our text a translation according to the language used by the application.

This works fine and dandy. However, problems arise when you have more than one instance of ‘Text’ that you wish to eager load.

Let us say that there is a ‘Product’ model containing a [i]title_id[/i] and a [i]description_id[/i] both referencing the ‘Text’ model. If we wish to create a list of our products, using [i]with[/i] in the AR criteria to eager load the translations for each product (to avoid executing too many queries), we run into a table name collision, where [i]language_code[/i] in our ‘Text’ needs to be disambiguated. Unfortunately, because its alias needs to be defined in the ‘relations’ array (because the [i]on[/i] condition in the ‘relations’ array is what defines the HAS_ONE relation), we can only give one alias for this class.

The unfortunate result of this situation is that we can never eager load more than one instance of the ‘Text’ class at a time, whereas it would (obviously) be much preferable to do as many as we like.

I have investigated ways around this, but so far have found none (including defining a static variable in the ‘Text’ class to be used in the relation [i]alias[/i] and then augmented each time, but looking at the CActiveRecord code, it seems that the ‘relations’ array is only used once to construct the ‘Text’ instance, so this is not viable).

I have no immediate solution to propose, but surely there must be some means of disambiguating table names even if only for the ‘relations’, by concatenating all the parents’ class names or some such thing.

I have seen a bug report on this issue (Bug report), but Quiang doesn’t want to do anything about it because of further complications it could cause with being able to use such an alias in the ‘relations’ conditions (surely we should be able to introduce some kind of placeholder for that).

Please let me know whether you agree with me and, of course, if you have any ideas for workarounds.