I'm a begginer in Symfony2...
I have a table "TUTORIEL" and an other table 'Groupe_de_categories' linked by 'id_groupe_categorie'
TABLE Tutoriels :
TABLE Groupe_de_categories
I need to count for each "titre_categorie_nv1" (here in my example 'Maison', 'Art&Loisir', 'Enseignement'...) how many "TUTORIEL" I have where "tutoriel_controle" = 'no'
Before to use Synfony2, I hade this code in PHP (works nice):
<?php
$query_nb_cat = "SELECT CATEGORIE, COUNT(*)
FROM Tutoriels
INNER JOIN Groupe_de_categories
ON TUTORIEL.id_groupe_categorie = Groupe_de_categories.id_groupe_categorie
WHERE tutoriel_controle='no'
GROUP BY CATEGORIE_TITLE";
$nb_cat = mysqli_query($BDD_connect, $query_nb_cat)or die(log_mysql($query_nb_cat));
$row_nb_cat = mysqli_fetch_assoc($nb_cat);
do {
$tableau_nb_cat[]=array(
'titre_cat_nv1'=>$row_nb_cat['titre_categorie_nv1'],
'compte_cat_nv1'=>$row_nb_cat['COUNT(*)'],
);
} while ($row_nb_cat = mysqli_fetch_assoc($nb_cat));
$val_cat=array(
'valeur_retour'=>$tableau_nb_cat
);
mysqli_free_result($nb_cat);
mysqli_close($BDD_connect);
?>
The result was something like that :
Maison => 3
Art&Loisir => 9
Enseignement => 14
...
How can I do this with Symfony2 ?
Here is my ORM :
Tutoriel 'Video2LearnBddBundle:Tutoriels':
Tutoriels
{
/**
* #var integer
*
* #ORM\Column(name="id_tutoriel", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTutoriel;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=70, nullable=false)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime", nullable=false)
*/
private $dateCreation = 'CURRENT_TIMESTAMP';
/**
* #var string
*
* #ORM\Column(name="nombre_de_vues", type="string", length=45, nullable=true)
*/
private $nombreDeVues;
/**
* #var string
*
* #ORM\Column(name="FAQs", type="string", length=45, nullable=true)
*/
private $faqs;
/**
* #var string
*
* #ORM\Column(name="exclusivite", type="string", nullable=false)
*/
private $exclusivite;
/**
* #var string
*
* #ORM\Column(name="eligible_promotion", type="string", nullable=false)
*/
private $eligiblePromotion;
/**
* #var string
*
* #ORM\Column(name="info_moderateur", type="string", length=300, nullable=true)
*/
private $infoModerateur;
/**
* #var string
*
* #ORM\Column(name="tutoriel_controle", type="string", nullable=false)
*/
private $tutorielControle = 'non';
/**
* #var string
*
* #ORM\Column(name="niveau_choix_categorie_autre", type="string", nullable=true)
*/
private $niveauChoixCategorieAutre;
/**
* #var string
*
* #ORM\Column(name="categorie_autre", type="string", length=45, nullable=true)
*/
private $categorieAutre;
/**
* #var \GroupeDeCategories
*
* #ORM\ManyToOne(targetEntity="GroupeDeCategories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_groupe_categorie", referencedColumnName="id_groupe_categorie")
* })
*/
private $idGroupeCategorie;
/**
* #var \Membres
*
* #ORM\ManyToOne(targetEntity="Membres")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_membre", referencedColumnName="id_membre")
* })
*/
private $idMembre;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="MotsCles", inversedBy="idTutoriel")
* #ORM\JoinTable(name="mots_cles_et_tutoriels",
* joinColumns={
* #ORM\JoinColumn(name="id_tutoriel", referencedColumnName="id_tutoriel")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="mots_cles", referencedColumnName="mots_cles")
* }
* )
*/
private $motsCles;
Groupe_de_categorie GroupeDeCategories:
<?php
namespace Video2Learn\BddBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* GroupeDeCategories
*
* #ORM\Table(name="Groupe_de_categories", indexes={
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv11_idx", columns={"titre_categorie_nv1"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv21_idx", columns={"titre_categorie_nv2"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv31_idx", columns={"titre_categorie_nv3"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv41_idx", columns={"titre_categorie_nv4"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv51_idx", columns={"titre_categorie_nv5"})
* })
* #ORM\Entity
*/
class GroupeDeCategories
{
/**
* #var integer
*
* #ORM\Column(name="id_groupe_categorie", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idGroupeCategorie;
/**
* #var \CategoriesNv1
*
* #ORM\ManyToOne(targetEntity="Video2Learn\BddBundle\Entity\CategoriesNv1", inversedBy="GroupeDeCategories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv1", referencedColumnName="titre_categorie_nv1")
* })
*/
private $titreCategorieNv1;
/**
* #var \CategoriesNv2
*
* #ORM\ManyToOne(targetEntity="CategoriesNv2")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv2", referencedColumnName="titre_categorie_nv2")
* })
*/
private $titreCategorieNv2;
/**
* #var \CategoriesNv3
*
* #ORM\ManyToOne(targetEntity="CategoriesNv3")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv3", referencedColumnName="titre_categorie_nv3")
* })
*/
private $titreCategorieNv3;
/**
* #var \CategoriesNv4
*
* #ORM\ManyToOne(targetEntity="CategoriesNv4")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv4", referencedColumnName="titre_categorie_nv4")
* })
*/
private $titreCategorieNv4;
/**
* #var \CategoriesNv5
*
* #ORM\ManyToOne(targetEntity="CategoriesNv5")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv5", referencedColumnName="titre_categorie_nv5")
* })
*/
private $titreCategorieNv5;
Thanks !
You can do it by using createQueryBuilder in your repository, or you can use your current query as NativeQuery
Here is a sample (I assume the name of your entities are Tutoriels and GroupeDeCategories)
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository('YourBundle:Tutoriels')
->createQueryBuilder('T')
->join('T.idGroupeCategorie', 'GC')
-->select('COUNT(GC.titreCategorieNv1) AS CT1')
->where("T.tutorielControle = 'no'")
->groupBy('GC.titreCategorieNv1')
->getQuery();
$result = $query->getScalarResult(); //This will return an array of the counts
In your entity I could not find CATEGORIE_TITLE to use in GroupBy and CATEGORIE to add in the selection; so I grouped them by titreCategorieNv1. You can add more fields for your select.
Maybe this link helps you more Symfony CreateQueryBuilder
I did that :
public function updateAction($type_update)
{
$request = Request::createFromGlobals();
$result = $request->isXmlHttpRequest();
if ($result === true) {
switch ($type_update) {
case "compteur_menu":
$em = $this->getDoctrine()->getManager();
$result = $em->createQuery("
SELECT TC.titreCategorieNv1, COUNT(TC.titreCategorieNv1) AS num
FROM Video2LearnBddBundle:Tutoriels T
INNER JOIN T.idGroupeCategorie GC
INNER JOIN GC.titreCategorieNv1 TC
WHERE T.tutorielControle='non'
GROUP BY TC.titreCategorieNv1"
)
->getResult();
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->setContent(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
default:
break;
}
}
}
You can do a repository (more infos here : http://symfony.com/fr/doc/current/book/doctrine.html )
And you could use Doctrine Query Language.
But I think your struture is wrong and it wold be better to have a category, this category has a parent category, ...
So you'll have for example a rootcatégory who has childs named "Bricolage", "Sport", ...
"Bricolage" would have, for exemple a category "Peinture" as child, and so on ;)
Related
i have two entities 'Panier' and 'Reservation' i want to add a one to many foreign key (the Entity 'Panier' can have many 'Reservation' and 'Reservation' has only one 'Panier' id ) , so i have to add a foreign key 'id' of 'Panier' in my Reservation entity class .
this is my Reservation class :
class Reservation
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="dateReservation", type="datetime", nullable=false)
*/
private $datereservation = 'CURRENT_TIMESTAMP';
/**
* #var integer
*
* #ORM\Column(name="quantite", type="integer", nullable=false)
*/
private $quantite;
/**
* #var float
*
* #ORM\Column(name="total", type="float", precision=10, scale=0, nullable=true)
*/
private $total;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=255, nullable=false)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="seat", type="string", length=255, nullable=false)
*/
private $seat;
/**
* #var integer
*
* #ORM\Column(name="payer", type="integer", nullable=true)
*/
private $payer;
/**
* #var string
*
* #ORM\Column(name="nomReservation", type="string", length=255, nullable=true)
*/
private $nomreservation;
/**
* #var \Event
*
* #ORM\ManyToOne(targetEntity="Event")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="event_id", referencedColumnName="id")
* })
*/
private $event;
/**
* #var \User
*
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
<?php
/** #Entity */
class Reservation {
/**
* #ManyToOne(targetEntity="Panier", inversedBy="reservations")
* #JoinColumn(name="panier_id", referencedColumnName="id")
*/
private $panier;
}
/** #Entity */
class Panier {
/**
* One Panier has many Reservations. This is the inverse side.
* #OneToMany(targetEntity="Reservation", mappedBy="panier")
*/
private $reservations;
public function __construct() {
$this->features = new ArrayCollection();
}
}
how i can to do this: I have OrderWork entity this for order and have relation manyToMany with Status entity. All work good, but i want have date for every saved and updated order.
* Order
*
* #ORM\Table(name="order_work")
* #ORM\Entity(repositoryClass="AppBundle\Repository\OrderWorkRepository")
*/
class OrderWork
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Client", cascade={"persist"})
* #ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
private $client;
/**
* #var string
*
* #ORM\Column(name="orderNumber", type="string", length=255)
*/
private $orderNumber;
/**
* #var string
*
* #ORM\Column(name="orderCity", type="string", length=255)
*/
private $orderCity;
/**
* #var date
*
* #ORM\Column(name="date", type="string", length=255)
*/
private $date;
/**
* #var \DateTime
*
* #ORM\Column(name="orderDate", type="string", length=255, options={"default": NULL})
*/
private $orderDate;
/**
* #var \DateTime
*
* #ORM\Column(name="returnDate", type="string", length=255, nullable=true)
*/
private $returnDate;
/**
* #var string
*
* #ORM\Column(name="device", type="string", length=255)
*/
private $device;
/**
* #ORM\ManyToOne(targetEntity="SurrogatePhone", cascade={"persist"})
* #ORM\JoinColumn(name="surrogate_id", referencedColumnName="id")
*/
private $surrogatePhone;
/**
* #var int
*
* #ORM\Column(name="orderType", type="integer")
*/
public $orderType;
/**
* #ORM\ManyToMany(targetEntity="Status")
* #ORM\JoinTable(name="order_status",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id", unique=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="status_id", referencedColumnName="id", unique=false)}
* )
*/
private $status;
How better resolve this solution?
Define date in your constructor (for creating):
class OrderWork
{
//...
public function __construct()
{
$this->date = new DateTime();
}
}
And update date field when updating:
$orderWork->setDate(new DateTime());
$em->flush();
Here's my table :
My Category entity (without getter/setter):
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255, nullable=true)
*/
private $slug;
/**
* #var int
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #var int
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #var int
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumn(name="root", referencedColumnName="id", onDelete="CASCADE")
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
In my controller, if I do this :
$category= $this->container->get('app.category.manager')->getCategoryBySlug($category_slug);
$root = $term->getRoot();
Doctrine execute 2 queries, one for the category itself, and one for the root of the category. I would like to create my own repository function to join the 2 entities in one query. I've tried so many things with the query builder, now I'm completly lost.
First, create a custom Repository class for your entity.
Then, paste the a method like the following into:
class CategoryRepository extends EntityRepository
{
public function getRootByCategorySlug($slug)
{
return $this->getEntityManager()
->createQueryBuilder()
->from('YourBundle:Category', 'c')
->where('c.slug = :slug')
->setParameter('slug', $slug)
->leftJoin('c.root', 'r') // Join the association
->select('r') // Fetch the association only
->getQuery()
->getResult()
;
}
}
And use it like follows:
$repo = $this->getDoctrine()->getManager()->getRepository('YourBundle:Category');
$rootCategory = $repo->getRootByCategorySlug('your_slug');
Does anyone have a clue why in the world I would be getting 20 minute page load times in dev in Symfony2? It just randomly happens to me. One day I will get fast load times, the next day I am twiddling my thumbs waiting for a page to load. What can I check/disable/enable/etc? Thanks!
Here is my latest page load:
Time: 298068 ms
Here is the Entity for PurchaseOrder
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="archived_po_number", type="string", length=50, nullable=true)
* #Common\Versioned
*/
private $archived_po_number;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=true)
* #Common\Versioned
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="show_locations", type="string", length=1, nullable=true)
* #Common\Versioned
*/
private $show_locations;
/**
* #var integer
*
* #ORM\Column(name="freight", type="decimal", precision=10, scale=2, nullable=true)
* #Common\Versioned
*/
private $freight;
/**
* #var integer
*
* #ORM\Column(name="pallets", type="integer", nullable=true)
* #Common\Versioned
*/
private $pallets;
/**
* #var integer
*
* #ORM\Column(name="boxes", type="integer", nullable=true)
* #Common\Versioned
*/
private $boxes;
/**
* #var text
* #ORM\Column(name="internal_notes", type="text", nullable=true)
* #Common\Versioned
*/
private $internal_notes;
/**
* #var text
* #ORM\Column(name="sales_rep_notes", type="text", nullable=true)
* #Common\Versioned
*/
private $sales_rep_notes;
/**
* #var string
*
* #ORM\Column(name="custom_purchase_order_number", type="string", length=255, nullable=true)
* #Common\Versioned
*/
private $custom_purchase_order_number;
/**
* #ORM\ManyToOne(targetEntity="WIC\CommonBundle\Entity\CustomOptions", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="purchase_order_class", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $purchase_order_class;
/**
* #ORM\ManyToOne(targetEntity="WIC\WarehouseBundle\Entity\Warehouse", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="generated_by_location", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $generated_by_location;
/**
* #ORM\ManyToOne(targetEntity="WIC\InventoryLocationBundle\Entity\InventoryLocation", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="receive_location", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $receive_location;
/**
* #ORM\ManyToOne(targetEntity="WIC\WarehouseBundle\Entity\Warehouse", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="company_name", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $company_name;
/**
* #ORM\ManyToOne(targetEntity="WIC\WarehouseBundle\Entity\Warehouse", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="ship_to", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $ship_to;
/**
* #ORM\ManyToOne(targetEntity="WIC\WarehouseBundle\Entity\Warehouse", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="bill_to", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $bill_to;
/**
* #ORM\ManyToOne(targetEntity="WIC\CommonBundle\Entity\CustomOptions", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="payment_terms", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $payment_terms;
/**
* #ORM\ManyToOne(targetEntity="WIC\CommonBundle\Entity\CustomOptions", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="fob", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $fob;
/**
* #ORM\ManyToOne(targetEntity="WIC\CommonBundle\Entity\CustomOptions", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="ship_via", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $ship_via;
/**
* #var datetime
*
* #ORM\Column(name="ship_by", type="datetime", nullable=true)
* #Common\Versioned
*/
private $ship_by;
/**
* #var datetime
*
* #ORM\Column(name="cancel_by", type="datetime", nullable=true)
* #Common\Versioned
*/
private $cancel_by;
/**
* #var datetime
*
* #ORM\Column(name="due_by", type="datetime", nullable=true)
* #Common\Versioned
*/
private $due_by;
/**
* #var string
*
* #ORM\Column(name="nbt", type="string", length=2, nullable=true)
* #Common\Versioned
*/
private $nbt;
/**
* #ORM\OneToMany(targetEntity="WIC\PurchaseOrderLineItemBundle\Entity\PurchaseOrderLineItem", mappedBy="purchaseOrder", cascade={"remove"}, fetch="EAGER")
*/
protected $purchaseOrderLineItem;
/**
* #ORM\OneToMany(targetEntity="WIC\PurchaseOrderBundle\Entity\PurchaseOrderCharge", mappedBy="purchaseOrder", cascade={"remove"}, fetch="EAGER")
*/
protected $purchaseOrderCharge;
/**
* #ORM\OneToMany(targetEntity="WIC\PurchaseOrderBundle\Entity\PurchaseOrderPayment", mappedBy="purchaseOrder", cascade={"remove"}, fetch="EAGER")
*/
protected $purchaseOrderPayment;
/**
* #ORM\ManyToOne(targetEntity="WIC\SupplierBundle\Entity\Supplier", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="supplier_id", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
protected $supplier;
/**
* #ORM\ManyToOne(targetEntity="WIC\CommonBundle\Entity\CustomOptions", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="status_id", referencedColumnName="id", nullable=true)
* #Common\Versioned
*/
private $status;
/**
* #ORM\ManyToOne(targetEntity="WIC\UserBundle\Entity\User")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
* #Common\Blameable(on="create")
*/
private $createdBy;
/**
* #ORM\ManyToOne(targetEntity="WIC\UserBundle\Entity\User")
* #ORM\JoinColumn(name="updated_by", referencedColumnName="id")
* #Common\Blameable(on="update")
*/
private $updatedBy;
/**
* #ORM\ManyToOne(targetEntity="WIC\AccountBundle\Entity\Account", inversedBy="purchaseOrders")
* #ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false)
* #Common\Versioned
* #Common\Blameable(on="create")
*/
protected $account;
/**
* #var datetime $created
*
* #Common\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var datetime $updated
*
* #Common\Timestampable(on="update")
* #ORM\Column(type="datetime", nullable=true)
*/
private $updated;
/**
* #ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
private $deletedAt;
Here is my controller method listAction()
// verify access
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
$classIdentity = new ObjectIdentity('class', 'WIC\\PurchaseOrderBundle\\Entity\\PurchaseOrder');
if (false === $this->get('security.context')->isGranted('VIEW', $classIdentity)) {
throw new AccessDeniedException('Only an admin user has access to this section...');
}
}
// get user's account
$account = $this->getUser()->getAccount();
$search_form = $this->createForm(new PurchaseOrderSearchType());
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$search_form->bind($request);
// if ($search_form->isValid()) {
$data = $search_form->getData();
$purchaseOrders = $em->getRepository('WICPurchaseOrderBundle:PurchaseOrder')->getListBy($data);
// }
} else {
if($this->get('request')->query->get('letter')){
}else{
}
// Set the up the pagination statement...
$em = $this->getDoctrine()->getManager();
$dql = "SELECT p FROM WIC\PurchaseOrderBundle\Entity\PurchaseOrder p WHERE p.account=:account_id ORDER BY p.created desc";
$query = $em->createQuery($dql);
$query->setParameters(array(
'account_id' => $account->getId(),
));
$paginator = $this->get('knp_paginator');
$paginatorObject = $paginator->paginate(
$query,
$this->get('request')->query->get('page', 1),25
);
// $purchaseOrders = $em->getRepository('WICPurchaseOrderBundle:PurchaseOrder')->findByAccount($account->getId(),array('id' => 'DESC'));
}
return array(
'heading' => 'Purchase Order',
'sidebarLeftTitle'=>'Purchase Order Menu',
'purchaseOrders' => $paginatorObject,
'search_form' => $search_form->createView(),
);
By default in app_dev.php you have the profiler bar, click on the timer and you will have a good start to debug (timeline with main/sub request, etc)
The issue was in the OneToMany relationship code where it says fetch="EAGER". This was pulling in all sorts of unnecessary associations and db queries. When I removed it, the db queries went down to 4 per page instead of 4000.
Are you using x-debug or any PHP level profiling? You've either got some form of recursion happening or one of the steps in the security\http\firewall process is taking a very long time to complete.
My suggestion would be
Look at your stack-trace and find anywhere there are highly repeated events around the security\http\firewall code and investigate if they exist
Quickly step through your code using x-debug, and find where the delay is occurring. With a few page reloads you should be able to step into the section which is causing the long page load times.
If you are using profiling, make sure your created files aren't ridiculously verbose. I've seen this long page load issue happen before due to profiling, where each page load would create a 20Gb+ profiling file.
I've used Translatable with a personal translation; I've implemented PysTranslationand I've used ORM query hint in PysRepository. All of this works fine, the problem has been when I've translated the entity Genero. This entity has a many-to-many relationship with Pys entity and the above method doesn't work. How I can translate the $genNombre attribute of Generoentity?
/**
* Pys
*
* #ORM\Table(name="pys")
* #ORM\Entity(repositoryClass="Filmboot\PYSBundle\Entity\PysRepository")
* #Gedmo\TranslationEntity(class="Filmboot\PYSBundle\Entity\PysTranslation")
*/
class Pys
{
/**
* #var integer
*
* #ORM\Column(name="PYS_ID", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $pysId;
/**
* #var string
*
* #ORM\Column(name="PYS_STR", type="string", length=255, nullable=false)
* #Gedmo\Translatable
*/
private $pysStr;
/**
* #var string
*
* #ORM\Column(name="PYS_TITULO", type="string", length=255, nullable=true)
* #Gedmo\Translatable
*/
private $pysTitulo;
/**
* #var integer
*
* #ORM\Column(name="PYS_DURACION", type="integer", nullable=true)
*/
private $pysDuracion;
/**
* #var integer
*
* #ORM\Column(name="PYS_ANYO", type="integer", nullable=true)
*/
private $pysAnyo;
/**
* #var string
*
* #ORM\Column(name="PYS_PAIS", type="string", length=255, nullable=true)
* #Gedmo\Translatable
*/
private $pysPais;
/**
* #var string
*
* #ORM\Column(name="PYS_SINOPSIS", type="string", length=3000, nullable=true)
* #Gedmo\Translatable
*/
private $pysSinopsis;
/**
* #var string
*
* #ORM\Column(name="PYS_GUIONISTA", type="string", length=255, nullable=true)
*/
private $pysGuionista;
/**
* #ORM\ManyToOne(targetEntity="Filmboot\DirectorBundle\Entity\Director", cascade={"remove"})
* #ORM\JoinColumn(name="DIR_ID", referencedColumnName="DIR_ID", onDelete="CASCADE")
*/
private $director;
/**
* #var string
*
* #ORM\Column(name="PYS_IMAGEN", type="string", length=255, nullable=true)
*/
private $pysImagen;
/**
* #var string
*
* #ORM\Column(name="PYS_IMAGEN_GRANDE", type="string", length=255, nullable=true)
*/
private $pysImagenGrande;
/**
* #ORM\ManyToMany(targetEntity="\Filmboot\ActorBundle\Entity\Actor", mappedBy="peliculas", cascade={"remove"})
*/
private $actores;
/**
* #ORM\ManyToMany(targetEntity="\Filmboot\PYSBundle\Entity\Genero", mappedBy="peliculas", cascade={"remove"})
*/
private $generos;
/**
* #ORM\OneToMany(targetEntity="\Filmboot\PYSBundle\Entity\Premio", mappedBy="pys", cascade={"remove"})
* #ORM\JoinColumn(name="PRE_ID", referencedColumnName="PRE_ID", onDelete="CASCADE")
*/
private $premios;
/**
* #ORM\OneToMany(targetEntity="\Filmboot\UsuarioBundle\Entity\Voto", mappedBy="pys", cascade={"remove"})
* #ORM\JoinColumn(name="PYS_ID", referencedColumnName="PYS_ID", onDelete="CASCADE")
*/
private $votaciones;
/**
* #ORM\OneToMany(targetEntity="PysTranslation", mappedBy="object", cascade={"persist", "remove"})
*/
private $translations;
public function __construct()
{
$this->actores = new ArrayCollection();
$this->generos = new ArrayCollection();
$this->votaciones = new ArrayCollection();
$this->translations = new ArrayCollection();
}
public function getTranslations()
{
return $this->translations;
}
public function addTranslation(PysTranslation $t)
{
if (!$this->translations->contains($t)) {
$this->translations[] = $t;
$t->setObject($this);
}
}
This is Genero
<?php
namespace Filmboot\PYSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Genero
*
* #ORM\Table(name="genero")
* #ORM\Entity
*/
class Genero
{
/**
* #var integer
*
* #ORM\Column(name="GEN_ID", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $genId;
/**
* #var string
*
* #ORM\Column(name="GEN_NOMBRE", type="string", length=255, nullable=true)
* #Gedmo\Translatable
*/
private $genNombre;
/**
* #ORM\ManyToMany(targetEntity="\Filmboot\PYSBundle\Entity\Pys", inversedBy="generos")
* #ORM\JoinTable(name="P_GENERO",
* joinColumns={#ORM\JoinColumn(name="GEN_ID", referencedColumnName="GEN_ID")},
* inverseJoinColumns={#ORM\JoinColumn(name="PYS_ID", referencedColumnName="PYS_ID")}
* )
*/
private $peliculas;
This is PysTranslation
/**
* #ORM\Entity
* #ORM\Table(name="pys_translation", uniqueConstraints={#ORM\UniqueConstraint(name="lookup_unique_idx", columns={"locale", "object_id", "field"})})
*/
class PysTranslation extends AbstractPersonalTranslation
{
/**
* Convinient constructor
*
* #param string $locale
* #param string $field
* #param string $value
*/
public function __construct($locale, $field, $value)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($value);
}
/**
* #ORM\ManyToOne(targetEntity="Pys", inversedBy="translations")
* #ORM\JoinColumn(name="object_id", referencedColumnName="PYS_ID", onDelete="CASCADE")
*/
protected $object;
}
This is PysRepository
class PysRepository extends EntityRepository
{
public function findPeliculas()
{
$em = $this->getEntityManager();
$consulta = $em->createQuery('
SELECT p, a, d, g, pr, v
FROM PYSBundle:Pys p
JOIN p.actores a JOIN p.director d JOIN p.generos g JOIN p.premios pr JOIN p.votaciones v
ORDER BY p.pysTitulo ASC
');
return $consulta->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker')->getResult();
}
/**
*
* #param string $pysStr El slug de la pelĂcula
*/
public function findPys($pysStr)
{
$em = $this->getEntityManager();
$consulta = $em->createQuery('
SELECT p, a, d, g, pr, v
FROM PYSBundle:Pys p
JOIN p.actores a JOIN p.director d JOIN p.generos g JOIN p.premios pr JOIN p.votaciones v
WHERE p.pysStr = :pysStr
');
$consulta->setParameter('pysStr', $pysStr);
return $consulta->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker')->getSingleResult();
}
}
I've solved the problem by adding this line in Genero entity annotations:
/**
* Genero
*
* #ORM\Table(name="genero")
* #ORM\Entity
* #Gedmo\TranslationEntity(class="Filmboot\PYSBundle\Entity\GeneroTranslation")
*/
class Genero