doudeng5764 2012-10-06 16:20
浏览 36
已采纳

ActiveRecord和PHP:定义两个模型之间不同关联的最佳方式

I have models Page and Commit. Page has many Commits. But sometimes i need to get just one last commit for page, and sometimes to get history of page commits (20 last or all).

I wrote this code for models:

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'));
}

So what i need to do to have a chance for display all commits (['limit' => 20] for ex.)?

  • 写回答

1条回答 默认 最新

  • doufei1988 2012-10-06 17:27
    关注

    It's a bit of a workaround, but this should do it... kinda simulating scopes from 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'));
    }
    

    And then just use the 'scope' you need:

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

    It's not a really overall solution, but it should do the trick...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历