2013-07-31 96 views
1

样品型号:坚持序列化对象的学说

/** @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的客户端/服务器之间comunicate。 我需要从客户端

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

并持续获得JSON,保持电场“created_at”不变。这样做是这样的:

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

在这种情况下,对象被成功更新,但是,很明显,“created_at”字段被设置为从“新的日期时间”的新值。 我可以从数据库中得到一个管理实体,然后就改变“名”,但我不希望不必要的选择..

概括地说,我怎么能完成这样的事:

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

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

编辑

一对夫妇使用SqlLogger测试后,我意识到,法合并()执行SELECT来获取当前状态... 所以,我的解决方案,现在,是让反对我自己,只替换我想更新的值。喜欢的东西:

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

这种方式“选择”的数量是一样的,但我得到保持原有的值从不知从JSON获取属性。

回答

0

学说需要一个持久的实体能够定义哪个字段已被更新与否。

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

如果你的问题是只有一个DateTime,您可以使用“列”标注的“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; 
} 
+0

使用列定义的问题是,CURRENT_TIMESTAMP标志被限制为每个表只有一个列...你不能用它来自动设置创建的时间戳和上次更新的时间戳。 – nelsonec87

+0

我之所以接受是因为明显的第一句话:“学说需要一个坚持不懈的实体......”。它让我做了更多的测试,并发现merge()也在DB中执行select。 – nelsonec87