将datetime字段转换为主键会引发致命错误

Got*_*bel 2 mysql datetime symfony doctrine-orm

我想使用两个外键的组合加上datetime字段作为我的组合主键.

但我得到了一个

可捕获的致命错误:类DateTime的对象无法转换为C:\ development\xampp\htdocs\happyfaces\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php第1337行中的字符串

当我这样做的时候.一旦我id: true从我的YML实体声明中删除一切正常.

这里出现的问题是什么?它对我来说似乎是一个Symfony2或Doctrine2错误,因为如果我没有将datetime列声明为主键的一部分,则在数据库中设置日期时间.

有人可以提供帮助或建议吗?

cre*_*lem 8

它是不可能的,不推荐.主键关注原始数据类型,如IntegerString.大多数RDMS系统更喜欢Integer作为最高性能的主键.

看看:http://doctrine-orm.readthedocs.org/en/2.1/tutorials/composite-primary-keys.html

也许通过添加新的Doctrine数据类型可以解决方法.有了__toString()函数,但我认为Doctrine会强制你只使用原始数据类型.

class Foo
{
    private $bar = 'test';

    public function __toString()
    {
        return $this->bar;
    }
}

echo new Foo();
Run Code Online (Sandbox Code Playgroud)

您的错误通常意味着DateTime没有__toString()功能或不符合字符串.我从未测试它使用自定义数据类型作为主键.所以你要自己尝试一下.

看看:http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html

另一个尝试是用String作主键并设置你id

$entity->setId(new \DateTime()->format('yyyy/mm/dd'));
Run Code Online (Sandbox Code Playgroud)

这是一个类似的问题:Symfony/Doctrine:DateTime作为主键