【问题标题】:cakephp writing SQL statementcakephp编写SQL语句
【发布时间】:2012-08-06 03:58:02
【问题描述】:

我在使用 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_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

【问题讨论】:

  • 您的具体问题是什么?
  • 我正在尝试在添加表单中获取 template_id。查找功能没有得到 template_id 的
  • template_id基于什么??
  • 模板表中的template_id。我假设会话数据中的用户 id 查询 accounts_users 表,然后根据 user_id 检查 account_ids,然后 account_id 在模板表中提取模板 - id,我与在模板表中插入 account_id 非常相似
  • 此链接book.cakephp.org/2.0/en/core-libraries/behaviors/… 可能会对您有所帮助。

标签: sql cakephp


【解决方案1】:

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

如果 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'))));

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多