Cakephp 2.0 MySQL查询 [英] Cakephp 2.0 mysql query

查看:90
本文介绍了Cakephp 2.0 MySQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Cakephp 2.0的新手,但是我想查看两个表。我有以下表格:

I'm new in Cakephp 2.0, but I want to make a view of two tables. I have the following tables:

具有记录的hpsas:ciname,位置,状态

ldaps有记录:ciname,状态

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''  

如何使用正确的Cakephp 2.0语法制作模型和控制器?

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.

在Hpsas模型中定义了多对一关系。

In Hpsas model "many to one" relationship is defined.

class Hpsas extends AppModel {
    public $belongsTo = array(
        'uniqueAlias1' => array(
            'className'  => 'Ldaps',
            'foreignKey' => 'ciname'
        )
    );
/... 

在Ldaps模型中定义了一对多关系。

In Ldaps model "one to many" relationship is defined.

class Ldaps extends AppModel {
    public $hasMany = array(
        'uniqueAlias2' => array(
            'className'  => 'Hpsas',
            'foreignKey' => 'ciname'
        ),
    );
/...

现在,如果执行代码 $ this- > Hpsas-> find('all')在Hpsass控制器上,您可能会得到以下结果:

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.

这篇关于Cakephp 2.0 MySQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆