2011-07-18 85 views
7

使用“不同”我已经寻找了很长时间让这件事的工作。如何在Zend的数据库模型

我想的是要懂得我的用户在一个Zend分贝模式“不同的”让我选择了独特的用户的追随者。

我的数据库模型计算的追随者用户(在这里我需要添加“不同”)

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”

我的表结构

  • ID
  • 的article_id // ID谁是 'USER_ID' 写的文章。
  • USER_ID // USER_ID文章的所有者
  • follower_id //成员谁拥有此文章
  • 日期//日期下面跟随

'user_ID的' 可写各种文章,跟随者可以遵循同一作者的各种文章。我想做一个独特的追随者数量。当我想要什么的例子,如果一个追随者跟随一个作家的8篇它在计数被比作“1”。

我希望这将是足够清楚了解什么我试图去够。

随着亲切的问候,

尼基

回答

11

使用不同:

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

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

    return $rowCount; 
} 

编辑:编辑在问题得到用户的追随者的数量后。实际上,你需要使用不明显。我已经测试了以下查询工作,以获取数据是计数()的,

SELECT * FROM followers WHERE user_id = 1 GROUP BY user_id, follower_id

我没有测试的代码,但这样的事情应该工作:

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

您可以在“从”功能,可向上选择查询功能指定MySQL的功能。要使用从功能,您需要通过表名作为第一个参数,但是传递$这个(表格模型类)工作正常。

public function countFollowers($user_id) 
{ 
    $rowset = $this->fetchAll(
    $this->select() 
    ->from($this, array('DISTINCT user_id')) 
    ->where('user_id = ?', $user_id) 
); 

    return count($rowset); 
} 

[编辑]

根据您的编辑, '群' 也可以为你工作:

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

    return count($rowset); 
} 

这将组中的所有匹配的user_id成一个记录。因此,如果用户被发现,它将返回1,否则为0。

+0

太好了!这是工作,唯一的修改是在设置组“follower_id”事业ELS我们只得到USER_ID和多数民众将永远“1”。非常感谢! – Nicky

2

检索所有行只是为了得到一个计数罢工我作为矫枉过正。

可以使用这样的事情做一个计数:

​​
1

不写:

public function countFollowers($user_id) 
    { 
     $rowset = $this->fetchAll(
     $this->select() 
     ->from($this, array('DISTINCT user_id')) 
     ->where('user_id = ?', $user_id) 
    ); 

    return count($rowset); 
} 

但这:

public function countFollowers($user_id) 
{ 
    $rowset = $this->fetchAll(
    $this->select() 
    ->from($this, array('DISTINCT(user_id)')) 
    ->where('user_id = ?', $user_id) 
); 

    return count($rowset); 
} 

否则你将有一个错误至极貌似mysqli的编制错误:

Unknown column 'repertoire.distinct idRepertoireParent' in 'field list'

0

今天我试着在LEFT JOIN DISTINCT的情况下,它不能正常工作。但是,如果你通过添加一个组到DISTINCT列,它工作正常。

0

而且我们从官方手册

一个方法,只要使用“独特”

构建此查询:SELECT DISTINCT P “PRODUCT_NAME” FROM “产品” 为P

$select = $db->select() 
      ->distinct() 
      ->from(array('p' => 'products'), 'product_name');