将日期时间字段作为主键会引发致命错误
我想使用两个外键和日期时间字段的组合作为我的组合主键.
I would like to use the combination of two foreign keys plus the datetime field as my combined primary key.
但是我得到了一个
可捕获的致命错误:无法转换类 DateTime 的对象串入C:developmentxampphtdocshappyfacesvendordoctrineormlibDoctrineORMUnitOfWork.php第1337行
Catchable Fatal Error: Object of class DateTime could not be converted to string in C:developmentxampphtdocshappyfacesvendordoctrineormlibDoctrineORMUnitOfWork.php line 1337
当我这样做时.一旦我从我的 YML 实体声明中删除 id: true
,一切都会恢复正常.
when I do so. As soon as I remove the id: true
from my YML entity declaration everything works fine again.
这里出现了什么问题?对我来说,这似乎是一个 Symfony2 或 Doctrine2 错误,因为如果我不将 datetime 列声明为主键的一部分,则数据库中的日期时间设置得很好.
What is the problem that occurs here? It seems to be rather a Symfony2 or a Doctrine2 bug to me, because the datetime is set fine in the database if I don't declare the datetime column to be part of the primary key.
有人可以提供帮助或建议吗?
Can anyone help or advise?
推荐答案
这是不可能的,也不推荐.对于主键,重点关注原始数据类型,例如 Integer
或 String
.大多数 RDMS 系统更喜欢 Integer
作为主键以获得最大性能.
Its not possible and not recommended. For primary key focus on primitive data types such as Integer
or String
. The most RDMS System prefer Integer
as primary key for maximum performance.
看看:http://doctrine-orm.readthedocs.org/en/2.1/tutorials/composite-primary-keys.html
也许可以通过添加新的 Doctrine 数据类型来解决问题.使用 __toString()
函数,但我认为 Doctrine 会强制您只使用原始数据类型.
Maybe a workaround could work by adding a new Doctrine data type. With a __toString()
function, but I think Doctrine will force you to use primitive data types only.
class Foo
{
private $bar = 'test';
public function __toString()
{
return $this->bar;
}
}
echo new Foo();
您的错误通常意味着 DateTime
没有 __toString()
函数或与字符串不兼容.我从未测试过它使用自定义数据类型作为主键.所以你必须自己尝试一下.
Your error means in general DateTime
has no __toString()
function or is not string compatible. I never tested it to use a custom data type as primary key. So you've to try it yourself.
看一看:http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html
另一个尝试是使用 String
作为主键并使用
Another try is use String
as Primary key and set your id
with
$entity->setId(new DateTime()->format('yyyy/mm/dd'));
这是一个类似的问题:Symfony/Doctrine: DateTime as primary key
相关文章