Cakephp只获得过滤后的孩子

时间:2014-07-16 15:03:33

标签: php sql cakephp

在我的案例中,用户和问卷有很多关系。所以我使用user_questionnaires表存储用户问卷。

我希望为所有用户提供用户问卷调查表。

我的手动查询。

SELECT `User`.`name` , `User`.`surname` , `User`.`email_personal` , `User`.`rf_id` , `User`.`gender` , `User`.`height` , `UserQuestionary`.`id`
FROM `woa`.`users` AS `User`
LEFT JOIN `woa`.`user_questionaries` AS `UserQuestionary` ON ( `UserQuestionary`.`user_id` = `User`.`id`
AND `UserQuestionary`.`questionary_id` =1 )
WHERE `User`.`role` =1

所以我写下面的paginate查询(我也需要分页)。

$paginate = array(
    'conditions' => array(
        'User.role' => 1,                
    ),
    'fields' => array(
        'User.name',
        'User.surname',
        'User.email_personal',
        'User.rf_id',
        'User.gender',
        'User.height',
        'UserQuestionary.id'
    ),
    'joins' => array(
        array(
            'alias' => 'UserQuestionary',
            'table' => 'user_questionaries',
            'type' => 'LEFT',
            'conditions' => 'UserQuestionary.user_id = User.id AND UserQuestionary.questionary_id = ' . $id
        )
    ),
    'limit' => 10,
    'order' => array(
        'name' => 'asc'
    ),
);

但它会进行多次查询并显示不需要的数据。

我的模特是

<?php
App::uses('AppModel', 'Model');

/**
 * UserQuestionariesUser Model
 *
 * @property User $User
 * @property Questionary $Questionary
 */
class UserQuestionariesUser extends AppModel
{
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useTable = 'user_questionaries';

    /**
     * hasAndBelongsToMany associations
     *
     * @var array
     */
    public $hasAndBelongsToMany = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Questionary' => array(
            'className' => 'Questionary',
            'foreignKey' => 'questionary_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
}

我如何进行上述查询? Cakephp有可能吗?

0 个答案:

没有答案