我有Users
和Followers
表。 Followers
与HasMany
有Users
关系,即任何用户都可以拥有多个关注者。
Array
(
[0] => Array
(
[User] => Array
(
[id] => 26
[seller_id_number] =>
[facebook_id] =>
[twitter_id] =>
)
[Followers] => Array
(
[0] => Array
(
[id] => 6
[user_id] => 2
[follower_id] => 26
[date_added] => 2017-09-22 03:58:21
[date_updated] => 2017-09-22 07:58:21
)
)
[1] => Array
(
[id] => 7
[user_id] => 52
[follower_id] => 26
[date_added] => 2017-09-22 16:35:23
[date_updated] => 2017-09-22 20:35:23
)
)
)
我需要分页(查找)用户和order by
最多关注者。
//$this->User->virtualFields['total_flw'] = 'COUNT(`User.Followers`)';
$this->paginate = array(
'conditions' => array( 'User.user_status' => 'user',
'User.soft_delete NOT' => 'on',
'User.status NOT' => 'inactive',
'User.id NOT' => $this->Session->read('User.id'),
$conditions,
),
'recursive' => 2,
//'order' => 'total_flw desc',
'paramType' => 'querystring',
'limit' => '24',
'maxLimit' => 100,
);
$listing_searched_users = $this->paginate('User');
尝试使用虚拟字段但未成功。任何帮助将不胜感激。
答案 0 :(得分:1)
您需要在查询中加入hasMany
模型,并在分页符的COUNT()
部分中执行ORDER BY
: -
$this->paginate = [
'joins' => [
[
'table' => 'followers',
'alias' => 'Follower',
'type' => 'LEFT',
'conditions' => 'Follower.user_id = User.id'
]
],
'group' => ['User.id'],
'order' => ['COUNT(User.id)' => 'DESC']
];
包含关联的模型在这里不起作用,因为关系是一对多关联,这意味着Cake必须执行两个单独的查询,这就是我们使用joins
的原因。