2012-08-06 135 views
1

我遇到了CakePHP和写sql查询的麻烦,我写了sql代码,但不知道如何在蛋糕中编写代码。cakephp写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用户
  • 账户的hasMany模板
  • 模板属于关联账户
  • 模板的hasMany领域
  • 领域属于关联模板

什么,我试图让我的发现声明中fieldscontroller,添加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。查找功能没有得到template_id的,而是抓住用户 - 编号

+0

你的具体问题是什么? – 2012-08-06 05:28:29

+0

我想要在添加窗体中获取template_id。查找功能没有得到template_id的 – user1393064 2012-08-06 05:29:41

+0

'template_id'的基础上什么? – 2012-08-06 05:30:57

回答

0

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

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

public $primaryKey = 'template_id'; 

http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey

和offcourse你得到你的要求。查询应该更像︰

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

但是,这是很难说,没有你的确切的表格布局。