Activerecord Relations Question

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)?

Hi Praxus

cna you post your ER diagram?

your relations() seems correctly

check also

$criteria=new CDbCriteria;

$criteria->condition = ‘…your condition…’;

$results=Text::model()->findAll($criteria)

Sure, in attachment. It’s just a part of it, there are other tables and columns that are not important.

I know, and I’ve been doing it like that. Just figured it would be easier and less code with just the relation.

I think your current language is missing in your relation declaration. If i correctly understand Active Record, you could use a scope for that.

I don’t think variables can be used in relation declaration.

Could you give example? I don’t know how. I think scopes can be used for current model only.

But perhaps I could add a new method regional($lang) that would make a query I’m using now.

That way I can still do $text->regional(Yii::app()->language).

check with that


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

Thank You, I got it working. It looks like this:


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.

Thank you all for your help.