cakephp编写SQL语句

cakephp编写SQL语句,sql,cakephp,Sql,Cakephp,我在cakephp和编写sql查询方面遇到了麻烦,我已经编写了sql代码,但不确定如何在cake中编写 `users` - id, name, address `accounts` - id, companyname, abn `accounts_users` - id, account_id, user_id `templates` - id, name, description, account_id `fields` - id, na

我在cakephp和编写sql查询方面遇到了麻烦,我已经编写了sql代码,但不确定如何在cake中编写

`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用户帐户
  • 帐户有许多模板
  • 属于帐户的模板
  • 模板有许多字段
  • 属于模板的字段
我试图在fieldscontroller中获取find语句,添加template\u 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;
这是迄今为止我在controller中字段中的代码:

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
指的是
用户
表id


错误是我试图在添加表单中获取模板id。find函数没有获取模板id,而是获取用户id,我认为您的字段名有问题。它们是否符合代码/名称约定? 请张贴模型的表格布局

如果模板id是表模板的主键,则应使用:

public $primaryKey = 'template_id';
在模板模型中。

当然你会得到你想要的。查询应该更像:

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

但是如果没有精确的表格布局,这很难说。

您的具体问题是什么?我正在尝试在add表单中获取模板id。find函数没有根据templates表中的template id获取template id的
template id
。我假设会话数据中的用户id查询accounts\u users表,然后根据用户id检查account\u id,然后account\u id位于提取模板id的模板表中,我的做法与在模板表中插入account\u id非常相似。此链接可能会帮助您。