如何在Zend DB模型中使用'distinct' [英] How to use 'distinct' in zend db model
问题描述
我已经搜索了很长时间才能使该功能正常工作.
I have search for a long time to get this thing work.
我想要知道的是如何在zend db模型中使用'distinct',以使我对用户关注者的选择唯一.
What I want is to know how I user the 'distinct' in a zend db model to make my selection for the followers of a user unique.
我的数据库模型为用户计算关注者(这里我需要添加'distinct')
My db model to count followers for a user (here I need to add the 'distinct')
public function countFollowers($user_id)
{
$rowset = $this->fetchAll("user_id = $user_id");
$rowCount = count($rowset);
if ($rowCount > 0) {
return $rowCount;
} else {
return $rowCount;
}
}
此函数是'扩展Application_Model_DbTable_Followers类Zend_Db_Table_Abstract'的一部分
This function is part of 'class Application_Model_DbTable_Followers extends Zend_Db_Table_Abstract'
我的表结构
- id
- article_id//由"user_id"撰写的文章的ID.
- user_id//文章的user_id所有者
- follower_id//已关注此文章的成员
- date//跟踪日期
'user_id'可以写成各种文章,关注者可以关注同一位作家的各种文章.我想增加一个唯一的关注者人数.例如,我想要的是,如果关注者关注一位作者的8篇文章,则必须将其与计数中的"1"进行比较.
'user_id' can be written various articles, the follower can follow various articles of the same writer. I want to make a unique follower count. As an example what I want, If a follower is following 8 articles of one writer it has to be compared to '1' in the count.
我希望这一点足够清楚,以了解我想要达到的目标.
I hope this will be clear enough to understand what I tried to reach.
以诚挚的问候,
Nicky
推荐答案
使用与众不同的方法:
public function countFollowers($user_id)
{
$select = $this->select()
->distinct()
->where('user_id = ?', $user_id);
$rowset = $this->fetchAll($select);
$rowCount = count($rowset);
return $rowCount;
}
在进行有问题的编辑后,获得用户的关注者数量.您实际上需要使用 group 不区分大小写.我已经测试了以下查询的工作原理,以获取要进行count()处理的数据,
After edit in question to get count of followers of a user. You actually need to use group NOT distinct. I have tested the following query works to fetch the data to be count()ed,
SELECT * FROM
followers
其中user_id = 1 GROUP BY user_id, follower_id
SELECT * FROM
followers
WHERE user_id = 1 GROUP BY user_id, follower_id
我还没有测试代码,但是类似的东西应该可以工作:
I have not tested the code, but something like this should work:
public function countFollowers($user_id)
{
$select = $this->select()
->where('user_id = ?', $user_id)
->group(array('user_id', 'follower_id'));
$rowset = $this->fetchAll($select);
$rowCount = count($rowset);
return $rowCount;
}
这篇关于如何在Zend DB模型中使用'distinct'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!