在Doctrine中保留序列化对象

时间:2013-07-31 02:13:55

标签: php doctrine-orm doctrine

样本模型:

/** @Entity */
class Person{
    /**
     * @Id @Column(type="integer", nullable=false)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /** @Column  */
    protected $name;

    /** @Column(type="datetime") */
    protected $created_at;

   //setters and getters...

   public function __construct($std){
        $this->id = $std->id;
        $this->nome = $std->nome;
        $this->created_at = new DateTime;
   }
}

我正在使用json在客户端/服务器之间进行通信。 我需要从客户端获取json

{ "id": 123, "name": "john" }

并坚持,保持字段“created_at”不变。这样做:

$p = json_decode($string);
$person = new Person($p);
entity_manager->merge($person);
entity_manager->flush();

在这种情况下,对象会成功更新,但很明显,“created_at”字段是使用“new DateTime”中的新值设置的。 我可以从数据库中获取一个托管实体,然后只需更改“名称”,但我不想要不必要的选择..

简而言之,我该如何执行以下操作:

UPDATE Person set name = "john" where id = 123

是否有注释忽略更新时的属性? 有没有办法将属性设置为不变?

修改

使用SqlLogger进行了几次测试后,我意识到方法merge()执行SELECT来获取当前状态...... 因此,我现在的解决方案是自己获取对象并仅替换我想要更新的值。类似的东西:

$std = json_decode($string);
$p = entity_manager->find('Person', $std->id);
$p->name = $std->name;
entity_managet->flush();

这样“选择”的数量是相同的,但我可以保留原始值来自我从json无法获得的属性。

1 个答案:

答案 0 :(得分:0)

Doctrine需要一个持久化实体才能定义哪个字段已更新。

http://apigen.juzna.cz/doc/doctrine/doctrine2.git/source-class-Doctrine.ORM.UnitOfWork.html#607-623

如果您的问题只是关于DateTime,您可以使用“Column”注释的“columnDefinition”部分来处理您的create_at值。

http://docs.doctrine-project.org/en/2.0.x/reference/annotations-reference.html#annref-column

例如使用mysql:

/** @Column(type="datetime", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP") */
protected $created_at;

//setters and getters...

public function __construct($std){
    $this->id = $std->id;
    $this->nome = $std->nome;
    //And so remove this initialization
    //$this->created_at = new DateTime;
}
相关问题