将datetime字段转换为主键会导致致命错误 [英] Taking a datetime field into primary key throws fatal error
问题描述
我想使用两个外键和datetime字段的组合作为我的组合主键。
I would like to use the combination of two foreign keys plus the datetime field as my combined primary key.
但是我得到一个
可追踪的致命错误:类DateTime的对象不能被转换
到
中的字符串C:\development\xampp\htdocs\\ \\ happyfaces\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php
line 1337
Catchable Fatal Error: Object of class DateTime could not be converted to string in C:\development\xampp\htdocs\happyfaces\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.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列声明为主键的一部分,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系统喜欢整数
作为最大性能的主键。
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
作为主键,并将 id
与
Another try is use String
as Primary key and set your id
with
$entity->setId(new \DateTime()->format('yyyy/mm/dd'));
这是一个类似的问题: Symfony / Doctrine:DateTime作为主键
Here is a similar question: Symfony/Doctrine: DateTime as primary key
这篇关于将datetime字段转换为主键会导致致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!