2014-01-15 22 views
1

我有2個表(1-n關係,「關鍵字」有很多「KeywordData」),他們被YYYYMM拆分。他們在同一個數據庫中。Phalcon模型 - 相同的表結構拆分由YYYYMM

例如,2014年1月的記錄位於keyword_201401 & keyword_data_201401中。 2014年2月的記錄關鍵字_201402 & keyword_data_201402

如何在模型中定義表名以便從正確的_YYYYMM表中讀寫值?

keyword_201401 (keyword_id, keyword, date) 
keyword_data_201401 (data_id, keyword_id, source) 

keyword_201402 (keyword_id, keyword, date) 
keyword_data_201402 (data_id, keyword_id, source) 

謝謝。

回答

0

這聽起來像是一個setSource()的工作。

您可以在模型(Keywords.php),如指定一個特定的表:

$this->setSource('keyword_201402'); 

不夠好,雖然,對不對?如果你希望它是動態的,你可以這樣做:

// Keyword.php 
function getAllKeywordsByDate($date) { 
    // $date might be 201401 or 201402 
    $this->setSource('keywords_' . $date); 

    // find the keywords from the table based on the date 
    $keywords = $this->find(); 

    // pass keywords to keyworddata to get related models 
    $dataset = (new KeywordData)->mergeKeywordAndKeywordData($keywords, $date); 

    // send the full dataset back 
    return $dataset; 
} 

// KeywordData.php 
function mergeKeywordAndKeywordData($keywords, $date) { 
    // $data might be 201401 or 201402 
    $this->setSource('keyword_data_' . $date); 

    $dataset = array(); 

    // find the keyword data from the table based on the date 
    foreach ($keywords as $keyword) { 
      $dataset[] = array(
       'keyword'  => $keyword, 
       'keyword_data' => $this->findByKeywordId($keyword->keyword_id) 
      ); 
    } 

    return $dataset; 
} 

你會最終有一個數組結束了,但是,這應該是非常接近你所需要的。它的效率並不比普通模型低,因爲1-n關係的性質是每個唯一ID記錄的新查詢。

所以,最後,在您的實現,你最終做:

$keywords = (new Keyword)->getAllKeywordsByDate('201401'); 

這可以通過以下方式interated過來:

foreach ($keywords as $keyword) { 
    print_r($keyword['keyword']); // keyword model ($keyword['keyword']->keyword) 
    print_r($keyword['keyword_data']); // same /\ 
}