开发者

How to get related values in Yii?

开发者 https://www.devze.com 2023-01-26 20:35 出处:网络
Schema: CITY ID (int) Name (string) Status (int) CITY_STATUS ID (int) Name (string) When I display a city (in the View view), I want to display the related CITY_STATUS.Name value, instead of the

Schema:

CITY
ID (int)
Name (string)
Status (int)

CITY_STATUS
ID (int)
Name (string)
  1. When I display a city (in the View view), I want to display the related CITY_STATUS.Name value, instead of the CITY.Status value

  2. When I add or update a city, I want to display a drop down of all CI开发者_如何学CTY_STATUS.Names in the drop down

How do I do this in Yii?


Guess I'll answer it myself.

Question 1

Relations are easier if you setup a foreign key in your database first. To do this you need to use MySQL (not SQLite) with the InnoDB engine (not MyISAM), and the field in question needs an index on it. Then, Gii will setup the relations function for you automatically. Otherwise, you'll have to do it manually in the relations() function of the model in question.

To use a related value in a View:

In protected/views/[model name]/view.php, in the CDetailView attributes array, change

'Status'

to

array('label'=>'Status', 'value'=>$model->RelationName->Name)

where RelationName is the name of the relation

To use a related value in an Index view, change protected/views/[model name]/_view.php (note the underscore), for example in this case you would change

$data->Status

to

$data->RelationName->Name

To use a related value in an Admin view, in the CGridView widget call, in the columns array, replace say

'Status'

with

array('name'=>'Status', 'header'=>'Status', 'value'=>'$data->RelationName->Name')

(note the use of the variable $data, and not say $model or $dataProvider). Still trying to figure out how to sort and filter...

Question 2

To use a drop-down menu, in protected/views/[model name]/_form.php:

change

<?php echo $form->textField($model,'Status'); ?>

to

<?php echo $form->dropDownList($model,'Status', CHtml::listData(Status::model()->findAll(), 'ID', 'Name')); ?>

el chief, you are a gentleman and a scholar.

0

精彩评论

暂无评论...
验证码 换一张
取 消