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 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?