Hi!
I have one question about usability of the code.
So, I have two tables :
CREATE TABLE Employee (
id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
departmentId SMALLINT UNSIGNED NOT NULL
COMMENT 'CONSTRAINT FOREIGN KEY (departmentId) REFERENCES Department(id)',
firstName VARCHAR(20) NOT NULL,
lastName VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
ext SMALLINT UNSIGNED NULL,
hireDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
leaveDate DATETIME NULL,
INDEX name (lastName, firstName),
INDEX (departmentId)
)
and
CREATE TABLE Department (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
deptHeadId MEDIUMINT UNSIGNED NOT NULL
COMMENT 'CONSTRAINT FOREIGN KEY (deptHeadId) REFERENCES Employee(id)',
name VARCHAR(40),
INDEX (deptHeadId),
UNIQUE (name)
)
I executed :
model Department
model Employee
crud Department
crud Employee
I want to concatenate two columns by “CONCAT(firstName, ’ ', lastName) as fullName” and get access to “fullName” column.
There’s my way how I do it :
- In Employee model I created beforeFind() method
class Employee extends CActiveRecord
{
.....
public function beforeFind()
{
$column = new CMysqlColumnSchema();
$column->dbType = 'varchar(255)';
$column->type = 'string';
$column->name = 'fullName';
$column->rawName = '`fullName`';
$column->isPrimaryKey = false;
$column->isForeignKey = false;
$column->allowNull = true;
$this->metaData->columns["fullName"] = $column;
}
.....
}
- And in one of view I created this code :
<?php
$criteria = new CDbCriteria();
$criteria->select = 'CONCAT(firstName, \' \', lastName) as fullName';
echo CHtml::activeDropDownList($model, 'deptHeadId', CHtml::listData(
Employee::model()->findAll($criteria), 'id', 'fullName'
));
?>
I think that my way is … some “dirty” and “not flexible”
Is there more graceful way to do it?
Tahnks.