cakephp - Creating Virtual Fields based on condtions -
good day. :) i'm new cakephp please bear me.
i have model student. student has attribute status integer. want create virtual fields based on student's status.
example:
status virtualfield 1 new student 2 new student - transferee 3 old student - shiftee 4 old student
any appreciated. thanks.
you didn't specify rdms you're using, i'm assuming mysql
using fixed strings
if want have virtualfield based on fixed strings, can achieve via case
in mysql , use define virtualfield
$this->mymodel->virtualfields['status_title'] = " case when status = 1 'new student' when status = 2 'new student - transferee' when status = 3 'old student - shiftee' when status = 4 'old student' else 'unkown status' end ";
or, define inside model itself;
class student extends appmodel { public $virtualfields = array( 'status_title' => " case when status = 1 'new student' when status = 2 'new student - transferee' when status = 3 'old student - shiftee' when status = 4 'old student' else 'unkown status' end ", ); }
using separate table
in answer, i'm assuming you're trying use fixed strings titles. it's better use separate database-table store status , (optionally) create virtualfield that;
your student model; app/model/student.php
class student extends appmodel {
public $belongsto = array( 'status' => array( 'type' => 'inner', ), };
}
your status model; app/model/status.php
class status extends appmodel {
public $usetable = 'statuses'; public $hasmany = array( 'student', };
}
your database-tables should this;
students;
id primary key, autonumber status_id id name varchar(50), -- etc.
statuses
id primary key, autonumber name varchar(50),
when retrieving student, status should automatically included;
for example
$data = $this->student->find('all', array( 'fields' => array( 'student.id', 'student.name', 'status.name', ), 'recursive' => 1, ));
should return students , status
if want add status-name 'virtual field' , have included inside 'student' array-index;
// create virtual field $this->student->virtualfields['status_name'] = 'status.name'; // , use inside query $data = $this->student->find('all', array( 'fields' => array( 'student.id', 'student.name', 'student.status_name', ), 'recursive' => 1, ));
Comments
Post a Comment