cakephp编写SQL语句

时间:2012-08-06 03:58:03

标签: sql cakephp

我遇到了cakephp和编写SQL查询的麻烦,我已经写出了sql代码,但我不确定如何在蛋糕中编写代码。

`users`          - id, name, address
`accounts`       - id, companyname, abn
`accounts_users` - id, account_id, user_id
`templates`      - id, name, description, account_id
`fields`         - id, name, description, template_id
  • 用户habtm帐户
  • 帐户habtm用户
  • accounts hasMany templates
  • templates belongsTo accounts
  • templates hasMany fields
  • 字段belongsTo templates

我想在fieldscontroller中获取我的find语句,添加template_id字段就是这样做

select t.id
from  template.t, account_users.au, user.u
where t.account_id=au.account_id AND
au.user_id=users.id;

这是我目前在控制器中的字段中的代码:

function add() {
    $this->Session->setFlash("Please create your required fields.");
    $templates = $this->Template->find('list', array(
        'fields' => array('id'),
        'conditions' => array('id'=> $this->Auth->user('id'))));
    $this->set('templates','$templates');

    if($this->request->is('post')) {
        $this->Field->create(); 

        if ($this->Field->save($this->request->data)) {     
            if ($this->request->data['submit'] == "type_1") { 
                $this->Session->setFlash('The field has been saved');  
                $this->redirect(array(
                    'controller' => 'fields',
                    'action' => 'add'));
            } 
            if ($this->request->data['submit'] == "type_2") {
                $this->Session->setFlash('The template has been saved'); 
                $this->redirect( array('controller' => 'templates','action' => 'index'));
            }
        } else {
            $this->Session->setFlash('The field could not be saved. Please, try again.'); 
        }
    }
}

当前正在打印的sql语句是

SELECT `Template`.`id` FROM `pra`.`templates` AS `Template` WHERE `id` = 14

id指的是users表格ID

错误是我试图在添加表单中获取template_id。 find函数没有获取template_id,而是抓取用户 - id

1 个答案:

答案 0 :(得分:0)

我认为您的字段名称有问题。它们是否符合代码/名称约定? 请发布模型的表格布局。

如果template_id是您应该使用的表格模板的主键:

public $primaryKey = 'template_id';

在模板模型中。 http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey

并且你可以得到你的要求。查询应该更像:

$templates = $this->Template->find('list', array(
    'fields' => array('Template.template_id'),
    'conditions' => array('User.id'=> $this->Auth->user('id'))));

但如果没有确切的桌面布局,那就很难说了。