【问题标题】:Phalcon Model - Same table structure split by YYYYMMPhalcon 模型 - 由 YYYYMM 拆分的相同表结构
【发布时间】:2014-01-15 09:57:17
【问题描述】:

我有 2 个表(1-n 关系,“关键字”有很多“关键字数据”),它们由 YYYYMM 拆分。它们在同一个数据库中。

例如,2014 年 1 月的记录在关键字_201401 和关键字_数据_201401 中。 2014 年 2 月在keyword_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)

谢谢。

【问题讨论】:

    标签: phalcon


    【解决方案1】:

    这听起来像是 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');
    

    可以通过以下方式进行交互:

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

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 2017-12-15
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多