2011-07-18 37 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');