簡體   English   中英

ActiveRecord和PHP:定義兩個模型之間不同關聯的最佳方法

[英]ActiveRecord & PHP: the best way to define different associations between two models

我有模型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]例如)?

這是一個變通辦法,但是應該這樣做...有點模仿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

這不是一個真正的整體解決方案,但應該可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM