【问题标题】:ActiveRecord & PHP: the best way to define different associations between two modelsActiveRecord & PHP:定义两个模型之间不同关联的最佳方式
【发布时间】:2012-10-06 16:20:59
【问题描述】:

我有模型 Page 和 Commit。页面有很多提交。 但有时我只需要获取页面的最后一次提交,有时需要获取页面提交的历史记录(最后 20 次或全部)。

我为模型编写了这段代码:

class Page extends ActiveRecord\Model {
    static $has_many = array(
        array('commits',
            'select'=> 'content',
            'order' => 'id DESC',
            'limit' => 1
        ));
}
class Commit extends ActiveRecord\Model {
    static $belongs_to = array(
        array('page'));
}

那么我需要做什么才能有机会显示所有提交(例如 ['limit' => 20])?

【问题讨论】:

    标签: php mysql sql activerecord orm


    【解决方案1】:

    这是一种解决方法,但应该这样做......有点模拟 Rails 的范围:

    class Page extends ActiveRecord\Model {
        static $has_many = array(
            array('limited_commits',
                'class_name' => 'Commit',
                'select'=> 'content',
                'order' => 'id DESC',
                'limit' => 1
            ),
            array('all_commits',
                'class_name' => 'Commit',
                'select' => 'content',
                'order' => 'id DESC'
            )
        );
    }
    class Commit extends ActiveRecord\Model {
        static $belongs_to = array(
            array('page'));
    }
    

    然后只需使用您需要的“范围”:

    Page::first->limited_commits
    Page::first->all_commits
    

    这不是一个真正的整体解决方案,但它应该可以解决问题......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多