dongying6179 2012-08-03 06:53
浏览 34
已采纳

使用Doctrine2在数据库中保留日期

I'm working with Symfony2 and Doctrine2 and I have a class called Domains with properties some names - strings and some dates. I use the following code to persists the information to the database:

public function createAction()
{
    $date = new \DateTime();
    $domain = new Domains();
    $domain->setMainDomain('new domain');
    $domain->setUser('new user');
    $domain->setSrv('server1');
    $domain->setStartDate($date->setDate(1992, 6, 3));
    $domain->setDueDate($date->setDate(1998, 7, 21));
    $domain->setPrevStartDate($date->setDate(1800, 9, 15));
    $domain->setPrevDueDate($date->setDate(1850, 10, 25));
    $domain->setNotified($date->setDate(2222, 3, 21), $date->setTime(12,01));

    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($domain);
    $em->flush();

    return new Response('Added a new domain with number '.$domain->getId());
} 

The problem is that all the dates has the value of the last one in the list :( In the example all of the dates become 2222-03-21. Can you please help me to fix this without creating a new DateTime object for every date which I want to persist in the datebase? Thank you very much in advance!

  • 写回答

1条回答 默认 最新

  • doufangpian5545 2012-08-03 07:11
    关注

    This is not a Symfony2/Doctrine2 problem.

    In PHP all objects are passed by reference, so you're essentially passing around same instance of the $date, so obviously it will set all dates to last one.

    There's no way to do this the way you want (using only 1 DateTime instance), but I really don't see a reason why would you want to anyway.

    To elaborate, why do you think this:

    $domain->setStartDate($date->setDate(1992, 6, 3));
    $domain->setDueDate($date->setDate(1998, 7, 21));
    $domain->setPrevStartDate($date->setDate(1800, 9, 15));
    ...
    

    is better than this:

    $domain->setStartDate(new \DateTime('1992-6-3'));
    $domain->setDueDate(new \DateTime('1998-7-21'));
    $domain->setPrevStartDate(new \DateTime('1800-9-15'));
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘