CAKEPHP - 查找相关模型的计数(有条件)

时间:2013-12-29 23:38:07

标签: cakephp

我有一个名为“User”的模型,它与“AdvertisementClicks”有一个hasMany关系。我想查找过去5天内至少有5次点击(例如)的所有用户。我目前有这个:

$params = array(
            'conditions' => array(
                'User.referrer_id' => NULL,
                'User.id !=' => $this->Session->read('MySite.User.id')
            ),
            'contain' => array(
                'AdvertisementClick' => array(
                    'conditions' => array(
                        'CAST(AdvertisementClick.created AS DATE) >=' => date('Y-m-d', strtotime("-4 days"))
                    )
                )
            )
        );


        $this->User->Behaviors->attach('Containable');
        $availableReferrals = $this->User->find('all', $params);

但是无论是否点击都可以找到所有用户。

如果可能的话,一旦发现这3个用户至少有5次点击,限制查找只返回3个用户。

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为AdvertisementClick属于User

$params = array(
    'conditions' => array(
        'User.referrer_id' => NULL,
        'User.id !=' => $this->Session->read('MySite.User.id'),
        'COUNT(AdvertisementClick.id) AS clickcount',
        'CAST(AdvertisementClick.created AS DATE) >=' => date('Y-m-d', strtotime("-4 days"))
    ),
    'group' => 'AdvertisementClick.id HAVING clickcount >= 5'
);



$availableReferrals = $this->User->AdvertisementClick->find(
    'all',
    $params
);

答案 1 :(得分:0)

在查询中使用group by,它将给出所需的结果:

$params = array(
                'conditions' => array(
                    'User.referrer_id' => NULL,
                    'User.id !=' => $this->Session->read('MySite.User.id'),
                    'COUNT(AdvertisementClick.id) AS clickcount',
                    'CAST(AdvertisementClick.created AS DATE) >' => date('Y-m-d', strtotime("-4 days"))

                ),
                'contain' => array(
                    'AdvertisementClick' => array(
                        'conditions' => array(
                            'CAST(AdvertisementClick.created AS DATE) >' => date('Y-m-d', strtotime("-4 days"))
                        )
                    )
                )
              'group'=>'AdvertisementClick.id HAVING clickcount >= 5'
            );


            $this->User->Behaviors->attach('Containable');
            $availableReferrals = $this->User->find('all', $params);