Search code examples
phpsymfonydoctrine-ormsonata-adminsymfony-sonata

Access to Doctrine in Entity


I have two Entity class: House and Car.

in Entity House class i have method:

<?php

namespace Acme\HouseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * House
 */
class House {
//...
  public function getRandomCar()
  {
      $em = $this->getDoctrine()->getManager();
      $car = $em->getRepository('AcmeCarBundle:Car')->find(rand(0,100));

      return $car->getName();
  }
}

but i dont have access to Doctrine in my Entity House class. How can i make it?


Solution

  • You need to write the function getRandomCar in your CarRepository (you'll have to create it)

    A simple rule is to never, ever write queries inside an entity (car, house....)

    Read more about Repositories

    Car.php

    /**
     * @ORM\Table(name="car")
     * @ORM\Entity(repositoryClass="Acme\CarBundle\Entity\CarRepository")
     */
    class Car 
    {
    }
    

    CarRepository.php

    class CarRepository extends EntityRepository  
    {
        public function getRandomCar() 
        {
            $qb = $this->createQuery('c');
            $qb->where('c.id = :id')
                ->setParameters(array('id' => rand(0,100)))
                ->getQuery();
    
            return $qb->execute();
        }
    }
    

    Then in your Controller,

    $em = $this->getDoctrine()->getManager();
    $car = $em->$em->getRepository('AcmeCarBundle:Car')->getRandomCar();
    $car->getName();