How can I access the EntityManager or a repository class inside a DataFixture in order to create a query?
If your fixture implements ContainerAwareInterface you have full access to the container and can obtain one of your entity-managers from there.
once you have the entity-manager you can get the repository or create a query using DQL or the querybuilder.
namespace Vendor\YourBundleBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadCharacterData implements FixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load()
{
$em = $this->container->get('doctrine')->getEntityManager('default');
// example using DQL
$query = $em->createQuery('SELECT u FROM YourBundle\Entity\User u WHERE u.name = your_name');
$users = $query->getResult();
// example query using repository
$repository = $em->getRepository('YourBundle:User');
$entities = $repository->findBy(array('name' => 'your_name'));
// example using queryBuilder
$qb = $repository->createQueryBuilder('u');
$qb
->where('u.name = :name')
->setParameter('name', 'your_name')
->orderBy('u.name');
$users = $qb->getQuery()->getResult();
// ...
}
Related
I would like to use entity manager inside entity and no idea for usage.
use Doctrine\Common\Persistence\ObjectManagerAware;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use SomeBundle\Entity\Boarding;
use SomeBundle\Entity\User;
class Entity extends ApiUserEntity implements ObjectManagerAware
{
private $em;
public function ___construct(User $user)
{
$this->board = $this->getData(123);
}
public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
{
$this->em = $objectManager;
}
private function getData($leadId)
{
//return gettype($this->em); //return null
$repository =$this->em->getRepository(Boarding::class);
$query = $repository->createQueryBuilder('b')
->where('b.lead = :lead')
->setParameter('lead', $leadId)
->getQuery();
$boards = $query->getResult();
return $boards;
}
}
Using this code get me error
Call to a member function getRepository() on null"
The entity manager is null also
//return gettype($this->em); //return null
Any idea for example usage?
You can try to create a repository like here. Just add
* #ORM\Entity(repositoryClass="App\Repository\EntityRepository")
or to YAML, Xml depends on your configuration and then create the repository file. Like this one:
// src/AppBundle/Repository/ProductRepository.php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM AppBundle:Product p ORDER BY p.name ASC'
)
->getResult();
}
}
i'm trying to understand how to do a QueryBuilder in a service so here is what i've done :
Create my service :
namespace OC\PlatformBundle\PurgerAdvert;
use Doctrine\ORM\EntityManager;
class PurgerAdvert
{
private $em;
public function __construct(EntityManager $em) {
$this->entityManager = $em;
}
public function purge($days)
{
$queryBuilder = $this->createQueryBuilder();
$queryBuilder->select('a')->from('OCPlatformBundle:Advert', 'a');
// get the Query from the QueryBuilder here ...
$query = $qb->getQuery();
return $result = $query->getResult();
}
}
Declare it in services.yml :
oc_platform.purger.advert:
class: OC\PlatformBundle\PurgerAdvert\PurgerAdvert
arguments: ['#doctrine.orm.entity_manager']
I remove the query because i've an error before that : "Attempted to call an undefined method named "createQueryBuilder" of class "OC\PlatformBundle\PurgerAdvert\PurgerAdvert"" I assume that i didn't call properly the entitymanager but i don't see my mistake ...
Thanks for your help :)
You may not want to type entityManager all the time, so a combination of both answers should work:
namespace OC\PlatformBundle\PurgerAdvert;
use Doctrine\ORM\EntityManager;
class PurgerAdvert
{
private $entityManager;
public function __construct(EntityManager $em) {
$this->entityManager = $em;
}
public function purge($days)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('a')->from('OCPlatformBundle:Advert', 'a');
// get the Query from the QueryBuilder here ...
$query = $qb->getQuery();
return $result = $query->getResult();
}
}
Try that, I think it should work.
I have an error when I would like to add a custom method with DQL Request.
Error:
Undefined method 'getAll'. The method name must start with either
findBy or findOneBy!
My Controller:(SheetController.php)
<?php
namespace Test\FrontBundle\Controller;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\FrontBundle\Entity\Sheet;
class SheetController extends Controller
{
public function sheetListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('TestFrontBundle:Sheet');
$sheets = $repository->getAll();
var_dump($sheets);
return $this->render('TestFrontBundle:Sheet:sheetList.html.twig');
}
public function sheetAction($id, Request $request)
{
$repository = $this->getDoctrine()->getManager()->getRepository('TestFrontBundle:Sheet');
$sheet = $repository->find($id);
if(!$sheet)
{
throw new EntityNotFoundException();
}
return $this->render('TestFrontBundle:Sheet:sheet.html.twig', array('sheet' => $sheet));
}
}
?>
My Repository:(SheetRepository.php)
<?php
namespace Test\FrontBundle\Entity;
/**
* SheetRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class SheetRepository extends \Doctrine\ORM\EntityRepository
{
public function getAll()
{
$qb = $this->createQueryBuilder('s');
$query = $qb;
$result = $query->getQuery()->execute();
return $result;
}
}
Please, Could you help me? :)
Why don't you use native Doctrine query findAll() for this?
public function sheetListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('TestFrontBundle:Sheet');
$sheets = $repository->findAll();
/***/
}
EDIT - With class repository:
class SheetRepository extends \Doctrine\ORM\EntityRepository
{
public function getAll()
{
return $this->createQueryBuilder('s')
->select('s')
->getQuery()
->getResult()
;
}
}
And in your controller : replace findAll() by getAll()
I am having an issue. Am new to symfony2 and I am trying to get a field of a repository in my controller without getting all of it. I tried with the findAll() and it works 'except that am getting all the fields'.
Here is my controller:
<?php
namespace Extranet\RepportsBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class UtilisateurController extends Controller
{
/**
* Retrieves utilisateurs name(called entite)
*
* #Route("/utilisateur", name="extranet_repports_utilisateur")
* #Template("ExtranetRepportsBundle:Utilisateur:index.html.twig")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
// $entity = $em->getRepository("ExtranetUtilisateurBundle:Utilisateur")->findAll(array());
$entity = $em->getRepository("ExtranetUtilisateurBundle:Utilisateur")
->createQueryBuilder(
'SELECT u.name FROM ExtranetUtilisateurBundle:Utilisateur u ORDER BY u.name ASC'
)
->getResult();
;
var_dump($entity);die();
return array('entity' => $entity);
}
}
// $em = $this->getDoctrine()->getManager();
// $query = $em->createQuery(
// 'SELECT p
// FROM AcmeStoreBundle:Product p
// WHERE p.price > :price
// ORDER BY p.price ASC'
// )->setParameter('price', '19.99');
// $products = $query->getResult();
I am trying to get only the username from the repository and the commented code below is the example from the symfony book
Thanks for your help
You can specify your properties in select() method of query builder which you want to select
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository("ExtranetUtilisateurBundle:Utilisateur");
$result= $entity->createQueryBuilder('u')
->select('u.name')
->orderBy('u.name')
->getQuery()
->getArrayResult();
I don't understand why I get the following error in my Symfony2 project:
Error: Call to a member function getQueryId() on a non-object
Here are my codes:
Bibliorepository:
<?php
namespace Xxxx\XxxxxBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* BiblioRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class BiblioRepository extends EntityRepository
{
public function wantAuthor($author)
{
$query = $this->_em->createQuery('SELECT b FROM XxxxBundle:Biblio b WHERE b.author = :author');
$query->setParameter('author', $author);
$result_author = $query->getResult();
return $result_author;
}
}
The getter:
/**
* Get queryId
*
* #return integer
*/
public function getQueryId()
{
return $this->queryId;
}
}
And the controller:
$author = $this->getUser()->getId();
$repository = $this
->getDoctrine()
->getManager()
->getRepository('XxxxBundle:Biblio');
$resultBiblio = $repository->wantAuthor($author);
$resultBiblio->getQueryId();
foreach ($resultBiblio as $id_query) {
$repository = $this
->getDoctrine()
->getManager()
->getRepository('XxXxBundle:Query');
$resultQuery = $repository->wantQuery($id_query);
$titles = $resultQuery->getQuery();
}
return $this->redirect($this->generateUrl("fos_user_profile_show"));
Thank you very much for your help ;)
$resultBiblio is an array with object. You invoke a method on array and this causes error.
You can invoke this method in foreach like
foreach ($resultBilbo as $singleResult){
$singleResult->getQueryId();
}
Var dump results wantAuthor($author) method and make sure you're getting the Author object in return. I bet you're not getting one.