Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Taking a datetime field into primary key throws fatal error

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: Object of class DateTime could not be converted to string in C:developmentxampphtdocshappyfacesvendordoctrineormlibDoctrineORMUnitOfWork.php line 1337

when I do so. As soon as I remove the id: true from my YML entity declaration everything works fine again.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...