I'm new in Cakephp 2.0, but I want to make a view of two tables. I have the following tables:
hpsas with records: ciname, location, status
ldaps with records: ciname, status
In my Controller I have the following syntax:
$this->Hpsa->query("SELECT `hpsas`.`ciname`, `hpsas`.`status`, `ldaps`.`ciname`, `ldaps`.`status` FROM `cmdb`.`hpsas`, `cmdb`.`ldaps` WHERE `hpsas`.`ciname` = `ldaps`.`ciname`;");
I got the following results as expected:
'hpsas' => array(
(int) 0 => array(
'hpsas' => array(
'ciname' => 'lsrv8001',
'status' => 'live'
),
'ldaps' => array(
'ciname' => 'lsrv8001',
'status' => 'indeployment''
How do I make the Model and Controller with the right Cakephp 2.0 syntax?
解决方案
Not sure what you already done and how your controller/model is named so I just put code samples which may help understand basic idea.
In Hpsas model "many to one" relationship is defined.
class Hpsas extends AppModel {
public $belongsTo = array(
'uniqueAlias1' => array(
'className' => 'Ldaps',
'foreignKey' => 'ciname'
)
);
/...
In Ldaps model "one to many" relationship is defined.
class Ldaps extends AppModel {
public $hasMany = array(
'uniqueAlias2' => array(
'className' => 'Hpsas',
'foreignKey' => 'ciname'
),
);
/...
Now if perform code $this->Hpsas->find('all') on Hpsass controller you will likely get following results:
array(
(int) 0 => array(
'uniqueAlias1' => array(
//hpsas table row with value
),
'uniqueAlias2' => array(
//ldaps table row where hpsas.ciname = ldaps.ciname
)
),
//rest hpsas table rows
)
Don't get confused about alias I used in samples, you could named whatever you want. They come handy when need dealing with multiples association for same model.
More detailed explained samples could be found on documentation.