如何在 zend db 模型中使用“distinct"

2021-12-29 00:00:00 sql mysql zend-framework

我已经搜索了很长时间才能让这件事起作用.

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;
    }
}

这个函数是'class Application_Model_DbTable_Followers extends 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.

亲切的问候,

尼基

推荐答案

Using distinct:

Using distinct:

public function countFollowers($user_id) 
{
    $select = $this->select()
              ->distinct()
              ->where('user_id = ?', $user_id);

    $rowset = $this->fetchAll($select);
    $rowCount = count($rowset);

    return $rowCount;
}

在有问题的编辑后获取用户的关注者数量.您实际上需要使用 group NOT distinct.我已经测试了以下查询工作来获取要 count()ed 的数据,

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 WHERE 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;
}

相关文章