Let's say I have the following database structure:
I have a
Classifier
table which contains a list of classifier types like "Eye color", "Hair color", "Shoe size", etc. It is linked to the Property
table which has lists of properties that correspond to the classifier. For example, it could have black
, brown
, white
and red
for hair type and US 8
, US 9
, and US 10
for shoe size. The Person
table is linked to the Property
table in a MANY_MANY fashion.
When this structure is declared in yii like so
'properties'=>array(self::MANY_MANY, 'Property', 'Xref(Person_id, Property_id)')
I can do something like this:
foreach ($person->properties as $property) {
echo ($property->classifier->name.': '.$property->name);
}
But what I am looking for is to address all properties separately, like $person->hairColor
or $person->shoeSize
.
Sure, I could declare multiple MANY_MANY relations with a condition (only on Classifier_id equal to some value). But for that I need to know all Classifier ids beforehand - not flexible at all.
But is there a way do declare this relation in yii so that it automatically parses the classifier? So that when I add a new row to the Classifier
table, say, build
and values like slim
or athletic
, I can just use $person->build
without declaring a new relation?
Not only that, I'd like to use these in CDbCriteria
, like so $my_criteria->compare('build.name', 'slim')
as opposed to both comparing Classifier_id
with what corresponds to build
and Property
with 'slim'
.
You can use the magic __get()
for that:
In your Person model (untested code sorry):
public function __get($prop)
{
if ($this->properties->hasAttribute($prop))
{
return $this->property->$prop;
}
return null;
// or maybe better
return parent::__get($prop);
}
Be arware that overriding CActiveRecords __get() might be a problem and is not recommended. You should check that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.