I have 3 tables: texts, texts_regional, languages.
texts_regional of course has parts of texts that go in different languages with columns: text_id, lang_id, title, description.
I would like to make a relation in the model Text so I can access regional data for current language easily.
What I have now is:
class Text extends CActiveRecord
{
public function relations()
{
return array(
'regional' => array(self::HAS_MANY, 'TextRegional', 'text_id', 'index'=>'lang_id'),
);
}
}
But that returns all the languages in an array and that’s way too much resources sometimes. Is there a way to make a relation to just get the language i request, like: $text->regional(Yii::app()->lang)?
class Text extends CActiveRecord
{
public function relations()
{
return array(
'regional' => array(self::HAS_MANY, 'TextRegional', 'text_id', 'index'=>'lang_id','condition'=>'TextRegional.lang_id='. <id of Yii::app()->language by map coding> ),
);
}
}
but test the <id of Yii::app()->language by map coding> by 1 2 3 etc first
class Text extends CActiveRecord
{
public function relations()
{
return array(
'regional' => array(self::HAS_ONE, 'TextRegional', 'text_id',
'condition'=>'regional.lang_id='.Yii::app()->user->LangId),
);
}
}
So I changed HAS_MANY to HAS_ONE so I get an object back and not array. "TextRegional.lang_id=" was throwing column not found so I put table alias there. And I also removed index because it is not necessary now.
EDIT:Oh and I’ve made a user variable that holds language id. That code is in init() method of main Controller class. I hope that is fine.