gpt4 book ai didi

symfony - 从数组到 Doctrine/ArrayCollection : entity id (date) issue

转载 作者:行者123 更新时间:2023-12-05 07:57:32 25 4
gpt4 key购买 nike

我有这个场景

实体

class Foo
{
/**
* @ORM\Id
* @ORM\Column(type="date")
*/
protected $date;

/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity"Bar", inversedBy="foo")
*/
protected $bar;

[...]
}

存储库

class FooRepository extends EntityRepository
{
public function dummyNameFunction()
{
$q = $this->createQueryBuilder('foo')
->//some dummy "components" added to builder
->getQuery()
;

//I need an ArrayCollection as I want to take advantage of
//Doctrine's ArrayCollection filter() function
return new ArrayCollection($q->getResult());
}
}

问题

只要我尝试从数据库中获取数据,我就会得到这个错误

ContextErrorException: Catchable Fatal Error: Object of class DateTime could not be converted to string in /path/to/project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2504

对我来说这是“非常清楚”:从对象的ArrayArrayCollection 的转换,Doctrine 想索引全新的ArrayCollection具有实体的 id,但由于键是日期时间,PHP 本身没有提供 __toString() 方法(或等效方法)。

我想到的可能的解决方案:

  • 添加一个整数字段作为 id。从 $date$bar 中删除 id 并设置约束以使其唯一。缺点:我有一个完全没用的文件。
  • Register一个学说自定义映射类型,基本上是一个带有 __toString 魔法方法的 Date。缺点:我现在不知道这是否有效,因为我还没有尝试过。。第二个解决方案似乎有效,但不适用于 __toString() 魔术方法。这有点“hack”,有点脏。您可以在下面找到解决方案 (*)

问题

  1. 与我的两种可能解决方案相比,有人知道更好或“更快”的方法吗?
  2. (附带问题)这是一个“真正的”问题吗?有可能 Doctrine2 开发人员没有考虑过将日期作为键吗?

肮脏的解决方案(*)

首先,您需要定义一个 Doctrine2 服装类型。你怎么做到的?
我在我的包中创建了一个文件夹(以保持 Doctrine2 原始包结构的安全)在 Doctrine\DBAL\Types。然后,在里面,我创建了这个类

<?php

namespace Company\BundleName\Doctrine\DBAL\Types;

use Doctrine\DBAL\Types\DateType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class CustomDate extends DateType
{
private $date_value;

public function getName()
{
return 'custom_date';
}

public function convertToPHPValue($value, AbstractPlatform $platform)
{
$date = parent::convertToPHPValue($value, $platform);
$this->date_value = $date;

return $date->format('Y-m-d');
}

public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value : null;
}
}

然后我添加了一个 boot() 方法来捆绑 Bootstrap 文件(您需要在 AppKernel.php 中注册捆绑的文件)

public function boot()
{
$em = $this->container->get('doctrine.orm.entity_manager');
Type::addType('custom_date', 'Company\BundleName\Doctrine\DBAL\Types\CustomDate');
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('custom_date','custom_date');
}

之后我进行了修改。 Foo 的 $date 变量的映射

  /**
* @ORM\Id
* @ORM\Column(type="custom_date")
*/
protected $date;

注意:如果你使用任何类型提示,记得正确更改getters和setters

最佳答案

似乎唯一的解决方案是创建一个全新的学说类型(我在这里称之为“肮脏的解决方案”),因为 UnitOfWork 需要字符串或整数才能正常工作。

来源:Doctrine 2 ORM DateTime field in identifier

关于symfony - 从数组到 Doctrine/ArrayCollection : entity id (date) issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26888635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com