Cakephp 2.0 mysql query

这一生的挚爱 提交于 2019-12-25 12:57:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12130317/cakephp-2-0-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!