cakephp在同一个类上有很多查询

时间:2014-10-09 05:43:32

标签: mysql cakephp cakephp-2.0

我正在使用此绑定

$this->Company->bindModel( array(
        'hasMany' => array(
                'CompanyContactPerson'=>array('conditions' => array('Company.name Like'=>'%'.$a.'%'),),
            ),
        'belongsTo' => array(
                'Status',
                'User'
            )
    ));
    $this->paginate = array(
        'limit' =>20,
        'conditions'=>$conditions,
        'order' =>array('Company.id'=> 'desc') ,
    );
$all_companies = $this->paginate('Company');

结果是这个查询。

SELECT `Company`.`id`, `Company`.`user_id`, `Company`.`name`, `Company`.`status_id`, `Company`.`email`, `Company`.`modified`, `Company`.`created`, `Status`.`id`, `Status`.`name`, `User`.`id`, `User`.`roll`, `User`.`username`, `User`.`email`, `User`.`password`, `User`.`first_name`, `User`.`last_name`, `User`.`gender`, `User`.`address`, `User`.`city`, `User`.`state`, `User`.`country`, `User`.`modified`, `User`.`created` 
FROM `companyinfo`.`companies` AS `Company` 
LEFT JOIN `companyinfo`.`statuses` AS `Status` ON (`Company`.`status_id` = `Status`.`id`) 
LEFT JOIN `companyinfo`.`users` AS `User` ON (`Company`.`user_id` = `User`.`id`) 
WHERE 1 = 1 ORDER BY `Company`.`id` desc LIMIT 20

它对CompanyContactPerson模型进行单独查询。所以我得到了公司表的所有结果。我只需要满足CompanyContactPerson条件的公司表中的那些行。我是如何实现这一目标的

2 个答案:

答案 0 :(得分:3)

将此信息放入您的公司模型中,以便它可以建立关系。 :)

public $hasMany = array(
        'CompanyContactPerson' => array(
            'className' => 'CompanyContactPerson',
            'foreignKey' => 'ForeignKeyinCompanyContactPerson',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => '',
            'dependent' => true
        )
    ));

或将其放入您的CompanyContactPerson模型

public $belongsTo = array(
        'Company' => array(
            'className' => 'Company',
            'foreignKey' => 'ForeignKeyofCompanyContactPersonTABLE',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

答案 1 :(得分:0)

在查询中使用限制

'limit' => 2, //int

因此只返回两行。

您的代码应该像

  'CompanyContactPerson'=>array('conditions' => 
                                          array('Company.name Like'=>'%'.$a.'%'),
                                'limit' => 2
   ),