dongwei1921 2010-10-20 13:42
浏览 33
已采纳

如何自我初始化Doctrine_Record(就好像Doctrine_Query那样)?

I have models that extend Doctrine_Record, and are directly mapped to one specific record from the database (that is, one record with given a given id, hardcoded statically in the class).

Now, I want the specific record class to initialize itself as if Doctrine_Query would. So, this would be the normal procedure:

$query = new Doctrine_Query();
$model = $query->from('Model o')->where('id = ?', 123)->fetchOne();

I would like to do something like this

$model = new Model();

And in the Model:

const ID = 123;

//note that __construct() is used by Doctrine_Record so we need construct() without the __
public function construct()
{
    $this->id = self::ID;
    //what here??
    $this->initialize('?????');
}

So for clarity's sake: I would like the object to be exactly the same as if it would be received from a query (same state, same attributes and relations and such).

Any help would be greatly appreciated: thank you.

  • 写回答

3条回答 默认 最新

  • dongyanfeng0546 2010-10-24 17:50
    关注

    The first thing I need to say is I'd put the constant in the class. So like this:

    class Application_Model_Person
    {
        const ID = 1234;
    }
    

    Then, a Doctrine method like Doctrine_Record::fetchOne() is always returning a (new) instance of the model and never merges the data with the record you're calling fetchOne() to. Doctrine is nevertheless able to merge a retreived record with another class, so it rather simple to do:

    class Application_Model_Person extends Doctrine_Record_Abstract
    {
        const ID = 1234;
    
        public function __construct($table = null, $isNewEntry = false)
        {
            // Calling Doctrine_Record::__construct
            parent::__construct($table, $isNewEntry);
    
            // Fetch the record from database with the id self::ID
            $record = $this->getTable()->fetchOne(self::ID);
            $this->merge($record);
        }
    }
    

    Then you're able to do:

    $model = new Application_Model_Person;
    echo $model->id; // 1234
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面