代码之家  ›  专栏  ›  技术社区  ›  user228395

如何自初始化条令记录(仿佛条令查询会)?

  •  0
  • user228395  · 技术社区  · 14 年前

    id ,在类中静态硬编码)。

    现在,我想让特定的记录类初始化自己,就像docine_Query那样。所以,这是正常的程序:

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

    我想做这样的事

    $model = new Model();
    

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

    所以为了清楚起见:我希望对象与从查询接收到的对象完全相同(相同的状态、相同的属性和关系等等)。

    3 回复  |  直到 14 年前
        1
  •  1
  •   Jurian Sluiman    14 年前

    我第一件事 需要 也就是说我会把常数放在课堂上。所以像这样:

    class Application_Model_Person
    {
        const ID = 1234;
    }
    

    然后,Doctrine_Record::fetchOne()这样的Doctrine方法总是返回模型的(新)实例,并且从不将数据与调用fetchOne()的记录合并。尽管如此,Doctrine仍然能够将检索到的记录与另一个类合并,因此做起来相当简单:

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

    $model = new Application_Model_Person;
    echo $model->id; // 1234
    
        2
  •  1
  •   Pelle    14 年前

    尽管对于同一数据类型(即表)有多个类实际上并不是ORM应该有的样子,但是您想要的可以在Doctrine中使用列聚合继承来完成。假设您使用的是Doctrine 1.2.x,您可以编写以下YML:

    Vehicle:
      columns:
        brand: string(100)
        fuelType: string(100)
    
    Car:
      inheritance:
        extends: Entity
        type: column_aggregation
        keyField: type
        keyValue: 1
    
    Bicycle:
      inheritance:
        extends: Entity
        type: column_aggregation
        keyField: type
        keyValue: 2
    

    $a = new Bicycle ,Doctrine会自动为您设置类型,因此您不必处理它。

        3
  •  0
  •   Pelle    14 年前

    我不认为模型实例在初始化后会决定挂起某个数据库条目。也就是说,你可以这样做:

    <?php
    class Model extends baseModel {
      public static function create($id = null)
      {
        if ($id === null) return new Model;
        return Doctrine::getTable('Model')->findeOneById($id);
      }
    }
    

    然后,你可以使用

    $newModel = Model::create();
    

    或者取一个已有的 14 (例如)使用

    $newModel = Model::create(14);
    

    或者,如果你想 123 而不是一个新项目 ,声明函数如下:

      public static function create($id = 123)