简体   繁体   中英

How to access data from two different table within single model/controller/form in yii

I am a new and beginner in yii, so i am asking that question.

Actually I have two different tables.

First is Language.

In there are two fields language(id, language_name) // here id is primary key.

Second is Scholar.

Scholar has 6 fields. Scholar(id, name, language_id, contact_no, country, email) //here id is primary key and whereas language_id is foreign key references to language.

Now Through Gii Code Generator i have generated model, controller and view with form generator of Language and Scholar, where i can add different languages and scholar too and i can manage it.

Now my question is When I click on manage scholars, it will show language id and i want to display here language name.

So can you help me how i can access here language name instead of language id.

I can get language name by below code written in view file.

<b><?php echo CHtml::encode($data->getAttributeLabel('language_id')); ?>:</b>
    <?php
        $criteria = new CDbCriteria ;
        $criteria->select='language_name';
        $qAlbums=Language::model()->findbyPk($data->language_id);
        echo $qAlbums->language_name;
    ?>

but I do not want to write such like of code in view, i want that, i get data directly like $data->language_name that comes in array.

Thanks

Let's say your Scholar class has a relation called language defined as follows in your model's relations() method:

'language' => array(self::BELONGS_TO, 'Language', 'language_id'),

You can now use <?php echo $data->language->language_name; ?> <?php echo $data->language->language_name; ?> in your views and language.language_name as field name for CDetailViews and CGridViews.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM