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'));
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!