ramsey / uuid-doctrine

:snowflake::file_cabinet: Allow the use of a ramsey/uuid UUID as Doctrine field type.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return the UUID as a string from the query builder

jean553 opened this issue · comments

Hi

I want to get the UUID as a string from the result of a query executed through the query builder.

I use the following code:

$query = $this->createQueryBuilder('a')           
    ->select('a.id AS id, at.name AS name')
    ...

The id field is the UUID, declared as follows into the entity file:

    /**                                                                             
     * @ORM\Id                                                                      
     * @ORM\Column(type="uuid", unique=true)                                        
     * @ORM\GeneratedValue(strategy="CUSTOM")                                       
     * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")           
     */                                                                             
    private $id;                                                                    

The query result returns the UUID as an object of type Uuid. Is there any way to get directly the UUID as a string from the query builder result ?

Thanks!

Are you able to cast the object to a string or call the toString() method on it?

Yes. The following code works and returns the UUID as a string:

$result = $query->getResult();                                                               
dump($result[0]['id']->toString());            

But it requires to call toString() on every query result. Is there any way to handle it directly from the DQL query ?

@jean553, unfortunately, I don't know the answer to this, but I'll ask around and see what I can find.

I was trying to move my project from incrementing IDs to uuid, and got stuck here! :D

@ramsey btw why is it that I would need the id to be of type UuidInterface and not just string
That would make things so much easier, and if I wanted to do any operation with the uuid, I could always convert the string to UuidInterface

The purpose of this library is to provide a Doctrine type that returns a ramsey/uuid object for UUID columns in a database.

If you just want UUID strings returned, there is a native Doctrine type for guid that already provides this. Take a look at that and see if it suits your needs: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/basic-mapping.html

@ramsey Exact. I misunderstood that point in the first place. Thanks for your explanation.

Sorry for the confusion. Glad I was able to help.

why nobody advised to use

$query = $this->createQueryBuilder('a')           
    ->select('a.id AS id, at.name AS name')
    ...
    ->getQuery()->getScalarResult()