如何在cakephp 2.x中编写以下查询

时间:2017-01-24 12:32:17

标签: cakephp cakephp-2.x

SELECT categories.category_name, categories.status, experts.name, experts.email, expert_categories.category_id, expert_categories.expert_id 
FROM categories, experts, expert_categories 
WHERE expert_categories.category_id = categories.id AND expert_categories.expert_id = experts.id AND categories.status = 'A'

2 个答案:

答案 0 :(得分:-1)

如果你知道自己想要什么,那么请使用预备声明:

 $db = $this->Category->getDataSource(); // if you make function in categories controller
 // $db = $this->getDataSource(); // if you make function in any model

 $result = $db->fetchAll("SELECT categories.category_name,categories.status,
       experts.name, experts.email, expert_categories.category_id, 
       expert_categories.expert_id FROM categories, experts, expert_categories 
       WHERE expert_categories.category_id = categories.id AND
       expert_categories.expert_id = experts.id AND categories.status = 'A'");

 // debug($result);

这就是为什么会做出cakephp准备好的声明。

见这里:Cakephp2 prepared statement

答案 1 :(得分:-1)

$this->Category->ExpertCategory->bindModel(array('belongsTo' => array(
    'Category' => array(
        'foreignKey' => false,
        'type'=>'INNER',
        'conditions' => array(
            'Category.id = ExpertCategory.category_id
             ExpertCategory.category_id = ' . $cat_id . ' and 
             Category.status = "A"'
         )
    ),
    'Expert' => array(
        'foreignKey' => false,
        'type'=>'INNER',
        'conditions' => array(
            'Expert.id = ExpertCategory.expert_id'
         )
     )
)), false);        

$allExpertArr = $this->Category->ExpertCategory->find('all');