Taking a datetime field into primary key throws fatal error

前端 未结 1 1711
生来不讨喜
生来不讨喜 2020-12-21 16:53

I would like to use the combination of two foreign keys plus the datetime field as my combined primary key.

But I get a

Catchable Fatal Error:

相关标签:
1条回答
  • 2020-12-21 17:18

    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.

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

    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();
    

    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.

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

    Another try is use String as Primary key and set your id with

    $entity->setId(new \DateTime()->format('yyyy/mm/dd'));
    

    Here is a similar question: Symfony/Doctrine: DateTime as primary key

    0 讨论(0)
提交回复
热议问题