How to get related values 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.
Neil McGuigan
I'm a Data Scientist (formerly Data Engineer) at a national Canadian bank I have the following certifications: AWS Certified Machine Learning Specialist AWS Certified Data Analytics Specialist AWS Certified DevOps Engineer Professional AWS Certified Developer Previously, I was a Data Scientist at Ritchie Bros. (market cap $5B) I'm also one of the authors of the book "RapidMiner: Data Mining Use Cases" I taught Data Mining for Management at UBC's graduate business school for a few years, as well as upper-level Economics at Royal Roads University Software Expertise: Statistics & Data Mining: Deep Learning, Python, SageMaker, Tableau Databases: PostgreSQL, MS SQL Server, Spark, Hive. See my blog at https://database-patterns.blogspot.com/ I'm good at Java, Python, Bash and SQL
Updated on June 22, 2022Comments
-
Neil McGuigan almost 2 years
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 CITY.Status value
When I add or update a city, I want to display a drop down of all CITY_STATUS.Names in the drop down
How do I do this in Yii?