Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Doctrine datatype only works in findBy not querybuilder

I have custom Datatype, which is working as expected when using FindBy... but doesn't when using query builder. Sorry for the long post, but I figure more info should help.

it's the same as this unanswered question: Doctrine 2 Custom Types

DataType:

...
class MyHappyType extends Type
{
    ...
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
       return 'hippies: '.$value;
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return 'doubleHippies: '.$value;
    }
    ...
    public function getName()
    {
        return 'hippies';
    }
}

Entity:

// Entity class

...
class Hippie
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer", unique=true)
     */
     protected $id;

   /*
    * @ORM\Column(type="hippies")
    */
    protected $Sandals;

}

Repository:

...
class HippiesRepository extends EntityRepository
{
    public function useQueryBuilder($sandals){
        $qb = $this->createQueryBuilder('hippie');
        $qb->select('hippie')
           ->where('hippie.Sandals = :sandals')
           ->setParameter('sandals', $sandals);

        return $qb->getQuery()->getResult();
    }
}

And finally, Controller:

public function hippiesAction()
{
    // this returns an entity with $hippie1->sandals == 'doubleHippies: hippies: red'
    // which is expected behaviour
    $hippie1 = $em->getRepository('HappyHippiesBundle:Hippie')->findOneBySandals('red');

    // this one returns no results, when checking queries run I see that
    // $sandals value isn't translated in to 'hippies: red'
    $hippie2 = $em->getRepository('HappyHippiesBundle:Hippie')->useQueryBuilder('red');
}

So in short, Datatypes aren't being converted when using QueryBuilder, only when using FindBy...

like image 803
offwhite Avatar asked Sep 04 '14 11:09

offwhite


1 Answers

You need to define the repository class in your entity configuration:

/**
 * @ORM\Entity(repositoryClass=""AcmeDemoBundle\Entity\HippiesRepository")
 */
class Hippie
{ 
    // ...
}

see Custom Repository classes for more information.

Update:

You may also want to get rid of the ->select('hippie'). When you use the method to create a QueryBuilder in the repository class, the method will automatically call the select and from methods for you (See the EntityRepository.php file for more info). In this case all you need to do is:

 $qb = $this->createQueryBuilder('hippie');
 $qb->where('hippie.Sandals = :sandals')
    ->setParameter('sandals', $sandals);

 return $qb->getQuery()->getResult();
like image 113
Onema Avatar answered Oct 11 '22 05:10

Onema