I have GoodsCats model with next relations:
public function relations(){
return array(
'GoodsCatsContent' => array(self::HAS_MANY, 'GoodsCatsContent', 'parent_id'),
);
}
And now I want to find all GoodsCats elements but with one child element (with specific language_id):
$cats = GoodsCats::model()->with(
array(
'GoodsCatsContent'=>array(
'on'=>'languages_id = 1'
)
)
)->findAll();
And recive an array where each elemt is like GoodsCats.id=>GoodsCatsContent.name:
CHtml::listData(cats, 'id', 'name')
But for now I’m getting an error GoodsCats.name not defined.
When I set GoodsCats relations as self::HAS_ONE all works good but I can’t change it for whole project.
Is it posible somehow set model()->with() to use not defined relation type but a specific one?
UPD my models rules:
GoodsCatsContent:
public function rules()
{
return array(
array('parent_id', 'required'),
array('active', 'numerical', 'integerOnly'=>true),
array('parent_id', 'length', 'max'=>10),
array('name, seo_title, seo_keywords, seo_description', 'length', 'max'=>255),
array('short_content, content', 'safe'),
array('id, parent_id, active, name, short_content, content, seo_title, seo_keywords, seo_description', 'safe', 'on'=>'search'),
);
}
GoodsCats:
public function rules()
{
return array(
array('active, prior', 'numerical', 'integerOnly'=>true),
array('photo', 'length', 'max'=>255),
array('id, photo, active, prior', 'safe', 'on'=>'search'),
);
}
You can’t dynamically change the relation type.
But, since you are sure that using
language_id = 1gives you only one relatedGoodsCatsContentrecord, you can do this instead of usinglistData():Because this is a HAS_MANY relation, each
GoodsCatswill have x number of related GoodsCatsContent records, and therefore the relation will return anarrayalways, even if there is only 1 related record, and an empty array if there is no related record. So when there is 1 related record, therelationName[0]will return that record.