I was creating a form. Certian fields of the form uses checkbox and may return multiple choices and I have to store all of those IDs to a single field separated by a comma or semicolon.
Now what I am looking to is how can I build a relation to that record in Yii Framework. Usually we use
'groupName' => array(self::BELONGS_TO, 'Lookup', 'group'),
'p_cpu' => array(self::BELONG开发者_JAVA技巧S_TO, 'Product', 'cpu'),
But how will I do it in the following manner
'p_additionalSoftwares' => array(self::BELONGS_TO, 'Product', 'additionalSoftwares'),
When the additionalSoftwares contain something like 2,8
As this is not a real BELONGS_TO relation with a foreign key you can not use Yii's built in functions. You may write a custom relation for this case based on CBaseActiveRelation or CActiveRelation, but I have no experience in that, but this may be the cleanest solution.
Another option would be to overwrite the get handler for your attribute, like*
public function getP_additionalSoftwares(){
//Use value from database in attributes and split into array with primary keys
$pks = explode(",",$this->attributes['p_additionalSoftwares']);
//Query database
$models = $this->findByPks($pks);
return $models;
}
In your view:
$model->p_additionalSoftwares
Should return an array of models, like a relation.
Note: This may impact performance, because you may get a large number of subrequests to the database, as the records are all lazy loaded.
**code untested*
精彩评论