I have below query in MySQL:
SELECT * FROM (orders)
INNER JOIN links ON orders.ref_id = links.id
INNER JOIN users ON links.user_id = users.id
WHERE links.user_id=2
And three entities in Symfony: order, link, user.
How can I write this in Doctrine Query Builder?
$repo = $em->getRepository('OrderBundle:Order');
$queryBuilder=$repo->createQueryBuilder('o');
$query = $queryBuilder
->select('o, l, u')
->innerJoin('c.ref_id', 'l')
->innerJoin('l.user_id', 'u')
->where('u.id=1')
->getQuery();
This doesn't work. I got below error:
[Semantical Error] line 0, col 84 near 'u WHERE u.id': Error: Class OrderBundle\Entity\Order has no association named user_id
I trying for two hours and this make me angry... Thanks in advance.
My order entity:
<?php
// src/OrderBundle/Entity/Order.php
namespace OrderBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\DateTime;
/**
* #ORM\Entity
* #ORM\Table(name="orders")
*/
class Order
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="OrderBundle\Entity\Order")
* #ORM\JoinColumn(name="ref_id", referencedColumnName="id")
*/
protected $ref_id;
/**
* #ORM\Column(type="datetime")
*/
protected $date_created;
/**
* #ORM\Column(type="string", length=60)
*/
protected $email;
/**
* #ORM\Column(type="string", length=60)
*/
protected $email2;
/**
* #ORM\Column(type="integer")
*/
protected $service;
/**
* #ORM\Column(type="string", length=20)
*/
protected $fromlang;
/**
* #ORM\Column(type="string", length=20)
*/
protected $tolang;
/**
* #ORM\Column(type="boolean")
*/
protected $academic;
/**
* #ORM\Column(type="string", length=40)
*/
protected $discipline;
/**
* #ORM\Column(type="text")
*/
protected $notes;
/**
* #ORM\Column(type="string")
*/
protected $file;
/**
* #ORM\Column(type="integer")
*/
protected $status;
/**
* #ORM\Column(type="integer")
*/
protected $cost;
/**
* #ORM\Column(type="string", length=2)
*/
protected $site;
public function __construct()
{
$this->date_created = new DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
*
* #return Order
*/
public function setDateCreated($dateCreated)
{
$this->date_created = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* Set email
*
* #param string $email
*
* #return Order
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email2
*
* #param string $email2
*
* #return Order
*/
public function setEmail2($email2)
{
$this->email2 = $email2;
return $this;
}
/**
* Get email2
*
* #return string
*/
public function getEmail2()
{
return $this->email2;
}
/**
* Set refId
*
* #param integer $refId
*
* #return Order
*/
public function setRefId($refId)
{
$this->ref_id = $refId;
return $this;
}
/**
* Get refId
*
* #return integer
*/
public function getRefId()
{
return $this->ref_id;
}
/**
* Set service
*
* #param integer $service
*
* #return Order
*/
public function setService($service)
{
$this->service = $service;
return $this;
}
/**
* Get service
*
* #return integer
*/
public function getService()
{
return $this->service;
}
/**
* Set fromlang
*
* #param string $fromlang
*
* #return Order
*/
public function setFromlang($fromlang)
{
$this->fromlang = $fromlang;
return $this;
}
/**
* Get fromlang
*
* #return string
*/
public function getFromlang()
{
return $this->fromlang;
}
/**
* Set tolang
*
* #param string $tolang
*
* #return Order
*/
public function setTolang($tolang)
{
$this->tolang = $tolang;
return $this;
}
/**
* Get tolang
*
* #return string
*/
public function getTolang()
{
return $this->tolang;
}
/**
* Set academic
*
* #param boolean $academic
*
* #return Order
*/
public function setAcademic($academic)
{
$this->academic = $academic;
return $this;
}
/**
* Get academic
*
* #return boolean
*/
public function getAcademic()
{
return $this->academic;
}
/**
* Set discipline
*
* #param string $discipline
*
* #return Order
*/
public function setDiscipline($discipline)
{
$this->discipline = $discipline;
return $this;
}
/**
* Get discipline
*
* #return string
*/
public function getDiscipline()
{
return $this->discipline;
}
/**
* Set notes
*
* #param string $notes
*
* #return Order
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
/**
* Get notes
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Set file
*
* #param string $file
*
* #return Order
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
* Set status
*
* #param integer $status
*
* #return Order
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set cost
*
* #param integer $cost
*
* #return Order
*/
public function setCost($cost)
{
$this->cost = $cost;
return $this;
}
/**
* Get cost
*
* #return \cost
*/
public function getCost()
{
return $this->cost;
}
/**
* Set site
*
* #param string $site
*
* #return Order
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Get site
*
* #return string
*/
public function getSite()
{
return $this->site;
}
}
Related
Im using adesigns/calendar-bundle to create a calendar on my symfony project.
I Can't get events from the DB when i access fc-load-events, This is my entity listener :
class CalendarEventListener
{
private $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function loadEvents(CalendarEvent $calendarEvent)
{
$startDate = $calendarEvent->getStartDatetime();
$endDate = $calendarEvent->getEndDatetime();
// The original request so you can get filters from the calendar
// Use the filter in your query for example
$request = $calendarEvent->getRequest();
$filter = $request->get('filter');
// load events using your custom logic here,
// for instance, retrieving events from a repository
$companyEvents = $this->entityManager->getRepository('CMRBundle:EventEntity')
->createQueryBuilder('company_events')
->where('company_events.event_datetime BETWEEN :startDate and :endDate')
->setParameter('startDate', $startDate->format('Y-m-d H:i:s'))
->setParameter('endDate', $endDate->format('Y-m-d H:i:s'))
->getQuery()->getResult();
// $companyEvents and $companyEvent in this example
// represent entities from your database, NOT instances of EventEntity
// within this bundle.
//
// Create EventEntity instances and populate it's properties with data
// from your own entities/database values.
foreach($companyEvents as $companyEvent) {
// create an event with a start/end time, or an all day event
if ($companyEvent->getAllDayEvent() === false) {
$eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), $companyEvent->getEndDatetime());
} else {
$eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), null, true);
}
//optional calendar event settings
$eventEntity->setAllDay(true); // default is false, set to true if this is an all day event
$eventEntity->setBgColor('#FF0000'); //set the background color of the event's label
$eventEntity->setFgColor('#FFFFFF'); //set the foreground color of the event's label
$eventEntity->setUrl('http://www.google.com'); // url to send user to when event label is clicked
$eventEntity->setCssClass('my-custom-class'); // a custom class you may want to apply to event labels
//finally, add the event to the CalendarEvent for displaying on the calendar
$calendarEvent->addEvent($eventEntity);
}
}
}
This is the error i get :
if ($companyEvent->getAllDayEvent() === false) {
$eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), $companyEvent->getEndDatetime());
} else {
$eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), null, true);
}
All the methods in evententity are not found : `getAllDayEvent(), getTitle(), getStartDatetime().
I have a public fonction getDaterdv in my entity :
(Ive changed the entity) to RDV :
<?php
namespace CMRBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RDV
*
* #ORM\Table(name="r_d_v")
* #ORM\Entity(repositoryClass="CMRBundle\Repository\RDVRepository")
*/
class RDV
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="datecrea", type="datetime")
*/
private $datecrea;
/**
* #ORM\Column(name="published", type="boolean")
*/
private $published = true;
/**
* #var \DateTime
*
* #ORM\Column(name="daterdv", type="datetime")
*/
private $daterdv;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="agentname", type="string", length=255)
*/
private $agentname;
/**
* #var string
*
* #ORM\Column(name="qualif", type="string", length=255)
*/
private $qualif;
/**
* #var int
*
* #ORM\Column(name="agentid", type="integer")
*/
private $agentid;
/**
* #var string
*
* #ORM\Column(name="company", type="string", length=255)
*/
private $company;
/**
* #var string
*
* #ORM\Column(name="comname", type="string", length=255)
*/
private $comname;
/**
* #var text
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var text
*
* #ORM\Column(name="adresse", type="text")
*/
private $adresse;
/**
* #var text
*
* #ORM\Column(name="ville", type="text")
*/
private $ville;
/**
* #var text
*
* #ORM\Column(name="telfixe", type="text")
*/
private $telfixe;
/**
* #var text
*
* #ORM\Column(name="telpor", type="text")
*/
private $telpor;
/**
* #var text
*
* #ORM\Column(name="tarif", type="text")
*/
private $tarif;
/**
* #var text
*
* #ORM\Column(name="support", type="text")
*/
private $support;
public function __construct()
{
$this->datecrea = new \Datetime();
$this->daterdv = new \DateTime();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set datecrea
*
* #param \DateTime $datecrea
*
* #return RDV
*/
public function setDatecrea($datecrea)
{
$this->datecrea = $datecrea;
return $this;
}
/**
* Get datecrea
*
* #return \DateTime
*/
public function getDatecrea()
{
return $this->datecrea;
}
/**
* Set daterdv
*
* #param \DateTime $daterdv
*
* #return RDV
*/
public function setDaterdv($daterdv)
{
$this->daterdv = $daterdv;
return $this;
}
/**
* Get daterdv
*
* #return \DateTime
*/
public function getDaterdv()
{
return $this->daterdv;
}
/**
* Set title
*
* #param string $title
*
* #return RDV
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set agentid
*
* #param integer $agentid
*
* #return RDV
*/
public function setAgentid($agentid)
{
$this->agentid = $agentid;
return $this;
}
/**
* Get agentid
*
* #return int
*/
public function getAgentid()
{
return $this->agentid;
}
/**
* Set company
*
* #param string $company
*
* #return RDV
*/
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* #return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set content
*
* #param string $content
*
* #return RDV
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set published
*
* #param boolean $published
*
* #return RDV
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* Set agentname
*
* #param string $agentname
*
* #return RDV
*/
public function setAgentname($agentname)
{
$this->agentname = $agentname;
return $this;
}
/**
* Get agentname
*
* #return string
*/
public function getAgentname()
{
return $this->agentname;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return RDV
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set ville
*
* #param string $ville
*
* #return RDV
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set telfixe
*
* #param string $telfixe
*
* #return RDV
*/
public function setTelfixe($telfixe)
{
$this->telfixe = $telfixe;
return $this;
}
/**
* Get telfixe
*
* #return string
*/
public function getTelfixe()
{
return $this->telfixe;
}
/**
* Set telpor
*
* #param string $telpor
*
* #return RDV
*/
public function setTelpor($telpor)
{
$this->telpor = $telpor;
return $this;
}
/**
* Get telpor
*
* #return string
*/
public function getTelpor()
{
return $this->telpor;
}
/**
* Set tarif
*
* #param string $tarif
*
* #return RDV
*/
public function setTarif($tarif)
{
$this->tarif = $tarif;
return $this;
}
/**
* Get tarif
*
* #return string
*/
public function getTarif()
{
return $this->tarif;
}
/**
* Set support
*
* #param string $support
*
* #return RDV
*/
public function setSupport($support)
{
$this->support = $support;
return $this;
}
/**
* Get support
*
* #return string
*/
public function getSupport()
{
return $this->support;
}
/**
* Set horaire
*
* #param string $horaire
*
* #return RDV
*/
public function setHoraire($horaire)
{
$this->horaire = $horaire;
return $this;
}
/**
* Get horaire
*
* #return string
*/
public function getHoraire()
{
return $this->horaire;
}
/**
* Set comname
*
* #param string $comname
*
* #return RDV
*/
public function setComname($comname)
{
$this->comname = $comname;
return $this;
}
/**
* Get comname
*
* #return string
*/
public function getComname()
{
return $this->comname;
}
/**
* Set qualif
*
* #param string $qualif
*
* #return RDV
*/
public function setQualif($qualif)
{
$this->qualif = $qualif;
return $this;
}
/**
* Get qualif
*
* #return string
*/
public function getQualif()
{
return $this->qualif;
}
}
Thanks for helping me
I have a public fonction getDaterdv in my entity :
(Ive changed the entity) to RDV :
<?php
namespace CMRBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RDV
*
* #ORM\Table(name="r_d_v")
* #ORM\Entity(repositoryClass="CMRBundle\Repository\RDVRepository")
*/
class RDV
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="datecrea", type="datetime")
*/
private $datecrea;
/**
* #ORM\Column(name="published", type="boolean")
*/
private $published = true;
/**
* #var \DateTime
*
* #ORM\Column(name="daterdv", type="datetime")
*/
private $daterdv;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="agentname", type="string", length=255)
*/
private $agentname;
/**
* #var string
*
* #ORM\Column(name="qualif", type="string", length=255)
*/
private $qualif;
/**
* #var int
*
* #ORM\Column(name="agentid", type="integer")
*/
private $agentid;
/**
* #var string
*
* #ORM\Column(name="company", type="string", length=255)
*/
private $company;
/**
* #var string
*
* #ORM\Column(name="comname", type="string", length=255)
*/
private $comname;
/**
* #var text
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var text
*
* #ORM\Column(name="adresse", type="text")
*/
private $adresse;
/**
* #var text
*
* #ORM\Column(name="ville", type="text")
*/
private $ville;
/**
* #var text
*
* #ORM\Column(name="telfixe", type="text")
*/
private $telfixe;
/**
* #var text
*
* #ORM\Column(name="telpor", type="text")
*/
private $telpor;
/**
* #var text
*
* #ORM\Column(name="tarif", type="text")
*/
private $tarif;
/**
* #var text
*
* #ORM\Column(name="support", type="text")
*/
private $support;
public function __construct()
{
$this->datecrea = new \Datetime();
$this->daterdv = new \DateTime();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set datecrea
*
* #param \DateTime $datecrea
*
* #return RDV
*/
public function setDatecrea($datecrea)
{
$this->datecrea = $datecrea;
return $this;
}
/**
* Get datecrea
*
* #return \DateTime
*/
public function getDatecrea()
{
return $this->datecrea;
}
/**
* Set daterdv
*
* #param \DateTime $daterdv
*
* #return RDV
*/
public function setDaterdv($daterdv)
{
$this->daterdv = $daterdv;
return $this;
}
/**
* Get daterdv
*
* #return \DateTime
*/
public function getDaterdv()
{
return $this->daterdv;
}
/**
* Set title
*
* #param string $title
*
* #return RDV
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set agentid
*
* #param integer $agentid
*
* #return RDV
*/
public function setAgentid($agentid)
{
$this->agentid = $agentid;
return $this;
}
/**
* Get agentid
*
* #return int
*/
public function getAgentid()
{
return $this->agentid;
}
/**
* Set company
*
* #param string $company
*
* #return RDV
*/
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* #return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set content
*
* #param string $content
*
* #return RDV
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set published
*
* #param boolean $published
*
* #return RDV
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* Set agentname
*
* #param string $agentname
*
* #return RDV
*/
public function setAgentname($agentname)
{
$this->agentname = $agentname;
return $this;
}
/**
* Get agentname
*
* #return string
*/
public function getAgentname()
{
return $this->agentname;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return RDV
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set ville
*
* #param string $ville
*
* #return RDV
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set telfixe
*
* #param string $telfixe
*
* #return RDV
*/
public function setTelfixe($telfixe)
{
$this->telfixe = $telfixe;
return $this;
}
/**
* Get telfixe
*
* #return string
*/
public function getTelfixe()
{
return $this->telfixe;
}
/**
* Set telpor
*
* #param string $telpor
*
* #return RDV
*/
public function setTelpor($telpor)
{
$this->telpor = $telpor;
return $this;
}
/**
* Get telpor
*
* #return string
*/
public function getTelpor()
{
return $this->telpor;
}
/**
* Set tarif
*
* #param string $tarif
*
* #return RDV
*/
public function setTarif($tarif)
{
$this->tarif = $tarif;
return $this;
}
/**
* Get tarif
*
* #return string
*/
public function getTarif()
{
return $this->tarif;
}
/**
* Set support
*
* #param string $support
*
* #return RDV
*/
public function setSupport($support)
{
$this->support = $support;
return $this;
}
/**
* Get support
*
* #return string
*/
public function getSupport()
{
return $this->support;
}
/**
* Set horaire
*
* #param string $horaire
*
* #return RDV
*/
public function setHoraire($horaire)
{
$this->horaire = $horaire;
return $this;
}
/**
* Get horaire
*
* #return string
*/
public function getHoraire()
{
return $this->horaire;
}
/**
* Set comname
*
* #param string $comname
*
* #return RDV
*/
public function setComname($comname)
{
$this->comname = $comname;
return $this;
}
/**
* Get comname
*
* #return string
*/
public function getComname()
{
return $this->comname;
}
/**
* Set qualif
*
* #param string $qualif
*
* #return RDV
*/
public function setQualif($qualif)
{
$this->qualif = $qualif;
return $this;
}
/**
* Get qualif
*
* #return string
*/
public function getQualif()
{
return $this->qualif;
}
}
It should be name of the entity field, but not the name of the database column specified in line
->where('company_events.event_datetime BETWEEN :startDate and :endDate')
so check, maybe it should be like
->where('company_events.eventDatetime BETWEEN :startDate and :endDate')
assuming that you are using camel case on your EventEntity field names using symfony coding style standards.
=============================
UPDATE
=============================
Now, when you posted your entity it is clear that it is not the one you trying to fetch from the database via repository.
$companyEvents = $this->entityManager->getRepository('CMRBundle:EventEntity')
->createQueryBuilder('company_events')
->where('company_events.event_datetime BETWEEN :startDate and :endDate')
->setParameter('startDate', $startDate->format('Y-m-d H:i:s'))
->setParameter('endDate', $endDate->format('Y-m-d H:i:s'))
->getQuery()->getResult();
Here your entity manager retrieving "EventEntity" instances from repository with name "CMRBundle:EventEntity", but to us you showed "RDV" and "CMRBundle\Repository\RDVRepository" to which it belongs to. As far as I understand from the part of the scope you shown - when some calendar event is raised you want to obtain all "event entities" from database which are in bounds of field values set in those event object that you passes to the listener. But it's unclear whether those RDV object that you have shown represent those "event entities" that you want to get from database. For now it looks like so and code related to "CMRBundle:EventEntity" just looks like some example code that your forgot to change. So, please, try to describe us the task and its context more carefully and tell if my assumption is right or wrong.
Introduction
I am using:
XAMPP with PHP v7.1.6
Symfony v3.3.4
Doctrine v2.5.4
StofDoctrineExtensionsBundle [1] in order to manage Tree structure.
Setting up
To setup Tree structure I used documentation on Symfony.com [2] followed by documentation on GitHub [3]. Then I proceeded with tree setup - used tree entity from example [4] and used code in [5] to create a tree.
I did setup the tree structure (that represents categories) called Category. I added several custom fields to the tree: for example is_active that represents active categories.
At the moment
I am using separate queries to get all Categories and corresponding Item counts, but i would like to get this info in just one, combined, query.
Question
Is it possible to get all Categories and corresponding Item counts in one query using DQL? If so then how?
MY CODE
Getting all Categories example
public function getCategoryTreeNodeArrayByRootId($category_tree_root_id)
{
$em = $this->getEntityManager();
$query = $em
->createQueryBuilder()
->select('ct')
->from('AppBundle:Category', 'ct')
->where('ct.root = :root')
->setParameter('root', $category_tree_root_id)
->orderBy('ct.root, ct.lft', 'ASC')
->getQuery();
$query->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);
$build_my_tree = $query->getArrayResult();
return $build_my_tree;
}
Getting element Item count that corresponds to Category example
public function getItemCountsByCategory($in_stock = true)
{
$em = $this->getEntityManager();
if ($in_stock === true)
{
// atrod preču skaitu pa kategorijām
$query = $em->createQueryBuilder()
->select('(i.category) as category_id, COUNT(i.id) as record_count')
->from('AppBundle:Item', 'i')
->where('i.in_stock != 0')
->groupBy('i.category')
->getQuery();
}
else if ($in_stock === false)
{
// atrod preču skaitu pa kategorijām
$query = $em->createQueryBuilder()
->select('(i.category) as category_id, COUNT(i.id) as record_count')
->from('AppBundle:Item', 'i')
->where('i.in_stock == 0')
->groupBy('i.category')
->getQuery();
}
$query->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);
$item_counts = $query->getArrayResult();
return $item_counts;
}
My Category entity:
<?php
namespace AppBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;
/**
* #Gedmo\Tree(type="nested")
* #ORM\Table(name="category")
* use repository for handy tree functions
* #ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*
* #var string
*/
private $category_name_lv;
/**
* #ORM\Column(type="boolean")
*/
private $is_active;
/**
* #Gedmo\TreeLeft
* #ORM\Column(type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumn(referencedColumnName="id", onDelete="CASCADE")
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
* One Category has Many Items.
* #ORM\OneToMany(targetEntity="Item", mappedBy="category")
*/
private $items;
public function __construct()
{
$this->items = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set categoryNameLv
*
* #param string $categoryNameLv
*
* #return Category
*/
public function setCategoryNameLv($categoryNameLv)
{
$this->category_name_lv = $categoryNameLv;
return $this;
}
/**
* Get categoryNameLv
*
* #return string
*/
public function getCategoryNameLv()
{
return $this->category_name_lv;
}
/**
* Set isFile
*
* #param boolean $isActive
*
* #return Category
*/
public function setIsActive($isActive)
{
$this->is_active = $isActive;
return $this;
}
/**
* Get isFile
*
* #return boolean
*/
public function getIsActive()
{
return $this->is_active;
}
/**
* Set lft
*
* #param integer $lft
*
* #return Category
*/
public function setLft($lft)
{
$this->lft = $lft;
return $this;
}
/**
* Get lft
*
* #return integer
*/
public function getLft()
{
return $this->lft;
}
/**
* Set lvl
*
* #param integer $lvl
*
* #return Category
*/
public function setLvl($lvl)
{
$this->lvl = $lvl;
return $this;
}
/**
* Get lvl
*
* #return integer
*/
public function getLvl()
{
return $this->lvl;
}
/**
* Set rgt
*
* #param integer $rgt
*
* #return Category
*/
public function setRgt($rgt)
{
$this->rgt = $rgt;
return $this;
}
/**
* Get rgt
*
* #return integer
*/
public function getRgt()
{
return $this->rgt;
}
/**
* Set root
*
* #param \AppBundle\Entity\Category $root
*
* #return Category
*/
public function setRoot(\AppBundle\Entity\Category $root = null)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* #return \AppBundle\Entity\Category
*/
public function getRoot()
{
return $this->root;
}
/**
* Set parent
*
* #param \AppBundle\Entity\Category $parent
*
* #return Category
*/
public function setParent(\AppBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \AppBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
/**
* Add child
*
* #param \AppBundle\Entity\Category $child
*
* #return Category
*/
public function addChild(\AppBundle\Entity\Category $child)
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* #param \AppBundle\Entity\Category $child
*/
public function removeChild(\AppBundle\Entity\Category $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Add item
*
* #param \AppBundle\Entity\Item $item
*
* #return Category
*/
public function addItem(\AppBundle\Entity\Item $item)
{
$this->items[] = $item;
return $this;
}
/**
* Remove item
*
* #param \AppBundle\Entity\Item $item
*/
public function removeItem(\AppBundle\Entity\Item $item)
{
$this->items->removeElement($item);
}
/**
* Get items
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getItems()
{
return $this->items;
}
/**
* toString
*
* #return string
*/
public function __toString()
{
return $this->getCategoryNameLv();
}
}
My Item entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\ItemRepository")
* #ORM\Table(name="item")
*/
class Item
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $unique_id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name_lv;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name_ru;
/**
* #ORM\Column(type="string", length=200)
*/
protected $category_sub;
/**
* #ORM\Column(type="string", length=500)
*/
protected $category_full;
/**
* #ORM\Column(type="string", length=500)
*/
protected $link_lv;
/**
* #ORM\Column(type="string", length=500)
*/
protected $link_ru;
/**
* #ORM\Column(type="string", length=500)
*/
protected $local_image_small_url;
/**
* #ORM\Column(type="string", length=500)
*/
protected $local_image_big_url;
/**
* #ORM\Column(type="string", length=500)
*/
protected $local_image_big2_url;
/**
* #ORM\Column(type="string", length=500)
*/
protected $local_image_big3_url;
/**
* #ORM\Column(type="string", length=3000)
*/
protected $description_lv;
/**
* #ORM\Column(type="string", length=3000)
*/
protected $description_ru;
/**
* #ORM\Column(type="decimal", scale=2)
*/
protected $price;
/**
* #ORM\Column(type="integer")
*/
protected $in_stock;
/**
* #ORM\Column(type="boolean")
*/
protected $is_exclusive;
/**
* #ORM\Column(type="boolean")
*/
protected $is_new;
/**
* #ORM\ManyToOne(targetEntity="Day", inversedBy="items")
* #ORM\JoinColumn(name="day_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $day;
/**
* Many Items have One Category.
* #ORM\ManyToOne(targetEntity="Category", inversedBy="items")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $category;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set uniqueId
*
* #param string $uniqueId
*
* #return Item
*/
public function setUniqueId($uniqueId)
{
$this->unique_id = $uniqueId;
return $this;
}
/**
* Get uniqueId
*
* #return string
*/
public function getUniqueId()
{
return $this->unique_id;
}
/**
* Set nameLv
*
* #param string $nameLv
*
* #return Item
*/
public function setNameLv($nameLv)
{
$this->name_lv = $nameLv;
return $this;
}
/**
* Get nameLv
*
* #return string
*/
public function getNameLv()
{
return $this->name_lv;
}
/**
* Set nameRu
*
* #param string $nameRu
*
* #return Item
*/
public function setNameRu($nameRu)
{
$this->name_ru = $nameRu;
return $this;
}
/**
* Get nameRu
*
* #return string
*/
public function getNameRu()
{
return $this->name_ru;
}
/**
* Set categorySub
*
* #param string $categorySub
*
* #return Item
*/
public function setCategorySub($categorySub)
{
$this->category_sub = $categorySub;
return $this;
}
/**
* Get categorySub
*
* #return string
*/
public function getCategorySub()
{
return $this->category_sub;
}
/**
* Set categoryFull
*
* #param string $categoryFull
*
* #return Item
*/
public function setCategoryFull($categoryFull)
{
$this->category_full = $categoryFull;
return $this;
}
/**
* Get categoryFull
*
* #return string
*/
public function getCategoryFull()
{
return $this->category_full;
}
/**
* Set linkLv
*
* #param string $linkLv
*
* #return Item
*/
public function setLinkLv($linkLv)
{
$this->link_lv = $linkLv;
return $this;
}
/**
* Get linkLv
*
* #return string
*/
public function getLinkLv()
{
return $this->link_lv;
}
/**
* Set linkRu
*
* #param string $linkRu
*
* #return Item
*/
public function setLinkRu($linkRu)
{
$this->link_ru = $linkRu;
return $this;
}
/**
* Get linkRu
*
* #return string
*/
public function getLinkRu()
{
return $this->link_ru;
}
/**
* Set localImageSmallUrl
*
* #param string $localImageSmallUrl
*
* #return Item
*/
public function setLocalImageSmallUrl($localImageSmallUrl)
{
$this->local_image_small_url = $localImageSmallUrl;
return $this;
}
/**
* Get localImageSmallUrl
*
* #return string
*/
public function getLocalImageSmallUrl()
{
return $this->local_image_small_url;
}
/**
* Set localImageBigUrl
*
* #param string $localImageBigUrl
*
* #return Item
*/
public function setLocalImageBigUrl($localImageBigUrl)
{
$this->local_image_big_url = $localImageBigUrl;
return $this;
}
/**
* Get localImageBigUrl
*
* #return string
*/
public function getLocalImageBigUrl()
{
return $this->local_image_big_url;
}
/**
* Set localImageBig2Url
*
* #param string $localImageBig2Url
*
* #return Item
*/
public function setLocalImageBig2Url($localImageBig2Url)
{
$this->local_image_big2_url = $localImageBig2Url;
return $this;
}
/**
* Get localImageBig2Url
*
* #return string
*/
public function getLocalImageBig2Url()
{
return $this->local_image_big2_url;
}
/**
* Set localImageBig3Url
*
* #param string $localImageBig3Url
*
* #return Item
*/
public function setLocalImageBig3Url($localImageBig3Url)
{
$this->local_image_big3_url = $localImageBig3Url;
return $this;
}
/**
* Get localImageBig3Url
*
* #return string
*/
public function getLocalImageBig3Url()
{
return $this->local_image_big3_url;
}
/**
* Set descriptionLv
*
* #param string $descriptionLv
*
* #return Item
*/
public function setDescriptionLv($descriptionLv)
{
$this->description_lv = $descriptionLv;
return $this;
}
/**
* Get descriptionLv
*
* #return string
*/
public function getDescriptionLv()
{
return $this->description_lv;
}
/**
* Set descriptionRu
*
* #param string $descriptionRu
*
* #return Item
*/
public function setDescriptionRu($descriptionRu)
{
$this->description_ru = $descriptionRu;
return $this;
}
/**
* Get descriptionRu
*
* #return string
*/
public function getDescriptionRu()
{
return $this->description_ru;
}
/**
* Set price
*
* #param string $price
*
* #return Item
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set inStock
*
* #param integer $inStock
*
* #return Item
*/
public function setInStock($inStock)
{
$this->in_stock = $inStock;
return $this;
}
/**
* Get inStock
*
* #return integer
*/
public function getInStock()
{
return $this->in_stock;
}
/**
* Set isExclusive
*
* #param boolean $isExclusive
*
* #return Item
*/
public function setIsExclusive($isExclusive)
{
$this->is_exclusive = $isExclusive;
return $this;
}
/**
* Get isExclusive
*
* #return boolean
*/
public function getIsExclusive()
{
return $this->is_exclusive;
}
/**
* Set isExclusive
*
* #param boolean $isNew
*
* #return Item
*/
public function setIsNew($isNew)
{
$this->is_new = $isNew;
return $this;
}
/**
* Get isExclusive
*
* #return boolean
*/
public function getIsNew()
{
return $this->is_new;
}
/**
* Set day
*
* #param \AppBundle\Entity\Day $day
*
* #return Item
*/
public function setDay(\AppBundle\Entity\Day $day = null)
{
$this->day = $day;
return $this;
}
/**
* Get day
*
* #return \AppBundle\Entity\Day
*/
public function getDay()
{
return $this->day;
}
/**
* Set category
*
* #param \AppBundle\Entity\Category $category
*
* #return Item
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
Conclusion
Please advise.
Thank you for your time and knowledge.
I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;
I've two doctrine entities with ManyToOne relationship:
/**
* #ORM\ManyToOne(targetEntity="Iballot\CmsBundle\Entity\PollingStation2", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Expose
*/
private $pollingStation2;
and I'd like get a specific one result for a given PollingStation2 ID and I've try that but doesn't work:
public function getPresidential($polId)
{
$qb = $this->createQueryBuilder('r');
$qb->where('r.pollingStation2 = :polling_station2_id')
->setParameter('polling_station2_id', $polId);
return $qb->getQuery()
->getResult();
}
Entities
namespace Iballot\CmsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PollingStation2
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Iballot\CmsBundle\Entity\PollingStation2Repository")
*/
class PollingStation2
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="verfierNumber", type="integer", length=255, nullable=true)
*/
protected $verfierNumber;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="verifier_number", type="string", length=255)
*/
private $verifierNumber;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #ORM\OneToMany(targetEntity="Iballot\CmsBundle\Entity\PollingStation2", mappedBy="pollingStation")
*/
protected $result;
/**
* #ORM\ManyToOne(targetEntity="Iballot\CmsBundle\Entity\Constituency", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $constituency;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function __toString() {
return $this->getName();
}
/**
* Set name
*
* #param string $name
*
* #return PollingStation2
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
*
* #return PollingStation2
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set verifierNumber
*
* #param integer $verifierNumber
*
* #return PollingStation2
*/
public function setVerifierNumber($verifierNumber)
{
$this->verifierNumber = $verifierNumber;
return $this;
}
/**
* Get verifierNumber
*
* #return integer
*/
public function getVerifierNumber()
{
return $this->verifierNumber;
}
/**
* Set verfierNumber
*
* #param integer $verfierNumber
*
* #return PollingStation2
*/
public function setVerfierNumber($verfierNumber)
{
$this->verfierNumber = $verfierNumber;
return $this;
}
/**
* Get verfierNumber
*
* #return integer
*/
public function getVerfierNumber()
{
return $this->verfierNumber;
}
/**
* Set constituency
*
* #param \Iballot\CmsBundle\Entity\Constituency $constituency
*
* #return PollingStation2
*/
public function setConstituency(\Iballot\CmsBundle\Entity\Constituency $constituency)
{
$this->constituency = $constituency;
return $this;
}
/**
* Get constituency
*
* #return \Iballot\CmsBundle\Entity\Constituency
*/
public function getConstituency()
{
return $this->constituency;
}
/**
* Constructor
*/
public function __construct()
{
$this->result = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add result
*
* #param \Iballot\CmsBundle\Entity\PollingStation2 $result
*
* #return PollingStation2
*/
public function addResult(\Iballot\CmsBundle\Entity\PollingStation2 $result)
{
$this->result[] = $result;
return $this;
}
/**
* Remove result
*
* #param \Iballot\CmsBundle\Entity\PollingStation2 $result
*/
public function removeResult(\Iballot\CmsBundle\Entity\PollingStation2 $result)
{
$this->result->removeElement($result);
}
/**
* Get result
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getResult()
{
return $this->result;
}
}
I want to find one data with findbyone option but by accesing the related object. Next you'll find the two of the entities Im using.
Caja.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
*
* #ORM\Entity
* #ORM\Table(name="caja")
*
*/
class Caja
{
/**
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Número carton")
*/
protected $numero_carton;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_inferior;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_superior;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Libretas omitidas")
*/
protected $omite_libreta;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Total libretas")
*/
protected $total_libretas;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Juego")
* #ORM\JoinColumn(name="juego_id", referencedColumnName="id")
* */
protected $juego;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario") **/
protected $usuario;
/**
* #ORM\Column(type="datetime", nullable=true)
* #GRID\Column(title="Fecha creación")
*/
protected $fecha_creacion;
/**
* #var boolean
*
* #ORM\Column(name="estado", type="string", length=50)
* #GRID\Column(title="Estado")
*/
protected $estado;
/*
* 1 = CREADO
* 2 = ASIGNADO_A_SUPERVISOR
* 3 = FINALIZADO_CON_EXITO
* 4 = FINALIZADO_CON_OBSERVACIONES
* 5 = DESHABILITADO
*
*/
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Libreta", mappedBy="caja", cascade={"remove", "persist"})
*/
protected $libretas;
public function __construct()
{
$this->fecha_creacion = new \DateTime();
$this->libretas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set numero_carton
*
* #param string $numeroCarton
* #return Caja
*/
public function setNumeroCarton($numeroCarton)
{
$this->numero_carton = $numeroCarton;
return $this;
}
/**
* Get numero_carton
*
* #return string
*/
public function getNumeroCarton()
{
return $this->numero_carton;
}
/**
* Set contiene_libreta_limite_inferior
*
* #param string $contieneLibretaLimiteInferior
* #return Caja
*/
public function setContieneLibretaLimiteInferior($contieneLibretaLimiteInferior)
{
$this->contiene_libreta_limite_inferior = $contieneLibretaLimiteInferior;
return $this;
}
/**
* Get contiene_libreta_limite_inferior
*
* #return string
*/
public function getContieneLibretaLimiteInferior()
{
return $this->contiene_libreta_limite_inferior;
}
/**
* Set contiene_libreta_limite_superior
*
* #param string $contieneLibretaLimiteSuperior
* #return Caja
*/
public function setContieneLibretaLimiteSuperior($contieneLibretaLimiteSuperior)
{
$this->contiene_libreta_limite_superior = $contieneLibretaLimiteSuperior;
return $this;
}
/**
* Get contiene_libreta_limite_superior
*
* #return string
*/
public function getContieneLibretaLimiteSuperior()
{
return $this->contiene_libreta_limite_superior;
}
/**
* Set omite_libreta
*
* #param string $omiteLibreta
* #return Caja
*/
public function setOmiteLibreta($omiteLibreta)
{
$this->omite_libreta = $omiteLibreta;
return $this;
}
/**
* Get omite_libreta
*
* #return string
*/
public function getOmiteLibreta()
{
return $this->omite_libreta;
}
/**
* Set total_libretas
*
* #param string $totalLibretas
* #return Caja
*/
public function setTotalLibretas($totalLibretas)
{
$this->total_libretas = $totalLibretas;
return $this;
}
/**
* Get total_libretas
*
* #return string
*/
public function getTotalLibretas()
{
return $this->total_libretas;
}
/**
* Set juego
*
* #param \PD\AppBundle\Entity\Juego $juego
* #return Caja
*/
public function setJuego(\PD\AppBundle\Entity\Juego $juego)
{
$this->juego = $juego;
}
/**
* Get juego
*
* #return \PD\AppBundle\Entity\Juego
*/
public function getJuego()
{
return $this->juego;
}
public function __toString()
{
return $this->getNumeroCarton();
}
/**
* Set usuario
*
* #param \PD\AppBundle\Entity\Usuario $usuario
* #return Caja
*/
public function setUsuario(\PD\AppBundle\Entity\Usuario $usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set fecha_creacion
*
* #param \DateTime $fechaCreacion
* #return Caja
*/
public function setFechaCreacion($fechaCreacion)
{
$this->fecha_creacion = $fechaCreacion;
return $this;
}
/**
* Get fecha_creacion
*
* #return \DateTime
*/
public function getFechaCreacion()
{
return $this->fecha_creacion;
}
/**
* Set estado
*
* #param string $estado
* #return Caja
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* #return string
*/
public function getEstado()
{
return $this->estado;
}
/**
* Add libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
* #return Caja
*/
public function addLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
//$this->libretas[] = $libretas;
//return $this;
$libretas->setCaja($this);
$this->libretas->add($libretas);
return $this;
}
/**
* Remove libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
*/
public function removeLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
$this->libretas->removeElement($libretas);
}
/**
* Get libretas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLibretas()
{
return $this->libretas;
}
}
Libreta.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* Libreta
*
* #ORM\Table()
* #ORM\Entity
*/
class Libreta
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Caja", inversedBy="libretas")
* #ORM\JoinColumn(name="caja_id", referencedColumnName="id", nullable=false)
* #Assert\Type(type="PD\AppBundle\Entity\Caja")
* #GRID\Column(field="caja.juego.nombre", title="Juego")
* #GRID\Column(field="caja.numero_carton", title="Caja")
*/
protected $caja;
/**
* #var string
*
* #ORM\Column(name="correlativo", type="string", length=10)
* #GRID\Column(title="Correlativo")
*/
private $correlativo;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario")
* #ORM\JoinColumn(name="vendedor_id", referencedColumnName="id", nullable=true)
* #Assert\Type(type="PD\AppBundle\Entity\Usuario")
* #GRID\Column(field="vendedor.nombre", title="Nombre vendedor")
* #GRID\Column(field="vendedor.apellidos", title="Apellidos vendedor")
*/
protected $vendedor;
/** #ORM\Column(name="precio_al_vendedor", type="decimal", scale=2) */
protected $precio_al_vendedor;
/** #ORM\Column(name="precio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Precio acumulado")
*/
protected $precio_acumulado;
/** #ORM\Column(name="premio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Premio acumulado")
*/
protected $premio_acumulado;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_asignacion_vendedor;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_estado_final;
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Ticket", mappedBy="libreta", cascade={"persist"})
*/
protected $tickets;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set correlativo
*
* #param string $correlativo
* #return Libreta
*/
public function setCorrelativo($correlativo)
{
$this->correlativo = $correlativo;
return $this;
}
/**
* Get correlativo
*
* #return string
*/
public function getCorrelativo()
{
return $this->correlativo;
}
/**
* Set precio_al_vendedor
*
* #param string $precioAlVendedor
* #return Libreta
*/
public function setPrecioAlVendedor($precioAlVendedor)
{
$this->precio_al_vendedor = $precioAlVendedor;
return $this;
}
/**
* Get precio_al_vendedor
*
* #return string
*/
public function getPrecioAlVendedor()
{
return $this->precio_al_vendedor;
}
/**
* Set precio_acumulado
*
* #param string $precioAcumulado
* #return Libreta
*/
public function setPrecioAcumulado($precioAcumulado)
{
$this->precio_acumulado = $precioAcumulado;
return $this;
}
/**
* Get precio_acumulado
*
* #return string
*/
public function getPrecioAcumulado()
{
return $this->precio_acumulado;
}
/**
* Set fecha_asignacion_vendedor
*
* #param \DateTime $fechaAsignacionVendedor
* #return Libreta
*/
public function setFechaAsignacionVendedor($fechaAsignacionVendedor)
{
$this->fecha_asignacion_vendedor = $fechaAsignacionVendedor;
return $this;
}
/**
* Get fecha_asignacion_vendedor
*
* #return \DateTime
*/
public function getFechaAsignacionVendedor()
{
return $this->fecha_asignacion_vendedor;
}
/**
* Set fecha_estado_final
*
* #param \DateTime $fechaEstadoFinal
* #return Libreta
*/
public function setFechaEstadoFinal($fechaEstadoFinal)
{
$this->fecha_estado_final = $fechaEstadoFinal;
return $this;
}
/**
* Get fecha_estado_final
*
* #return \DateTime
*/
public function getFechaEstadoFinal()
{
return $this->fecha_estado_final;
}
/**
* Set vendedor
*
* #param \PD\AppBundle\Entity\Usuario $vendedor
* #return Libreta
*/
public function setVendedor(\PD\AppBundle\Entity\Usuario $vendedor = null)
{
$this->vendedor = $vendedor;
return $this;
}
/**
* Get vendedor
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getVendedor()
{
return $this->vendedor;
}
/**
* Set caja
*
* #param \PD\AppBundle\Entity\Caja $caja
* #return Libreta
*/
public function setCaja(\PD\AppBundle\Entity\Caja $caja = null)
{
$this->caja = $caja;
return $this;
}
/**
* Get caja
*
* #return \PD\AppBundle\Entity\Caja
*/
public function getCaja()
{
return $this->caja;
}
/**
* Constructor
*/
public function __construct()
{
$this->tickets = new \Doctrine\Common\Collections\ArrayCollection();
//$this->caja = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
* #return Libreta
*/
public function addTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
//$this->tickets[] = $tickets;
$tickets->setLibreta($this);
$this->tickets->add($tickets);
return $this;
}
/**
* Remove tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
*/
public function removeTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
$this->tickets->removeElement($tickets);
}
/**
* Get tickets
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTickets()
{
return $this->tickets;
}
public function __toString()
{
return $this->correlativo;
}
/**
* Set premio_acumulado
*
* #param string $premioAcumulado
* #return Libreta
*/
public function setPremioAcumulado($premioAcumulado)
{
$this->premio_acumulado = $premioAcumulado;
return $this;
}
/**
* Get premio_acumulado
*
* #return string
*/
public function getPremioAcumulado()
{
return $this->premio_acumulado;
}
}
And what I would like to do is to find one next row ordered by field "fecha_creacion". This is what I have that get the next row but ordered by caja ID
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja' => 'DESC'));
But what I want to know if I can do something like "array('caja.fecha_creacion' => 'DESC'));". Until now, this part of the code isn't recognizing the "fecha_creacion" field
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja.fecha_creacion' => 'DESC'));
According to the doc, you can't pass a second parameter to the findOnyBy function.
But you can try to cheat by using the findBy methods and the position of this array :
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findNextLibreta(NULL, $actualPosicion);
...
And in your repository :
public function findNextLibreta($vendedor, $posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin(l.caja, 'c')
->where('l.vendedor = :vendedor')
->setParameter(':type', $type)
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
Thanks to #JulienBourdic I changed a little his proposal but him basically gave me the answer. The code is:
$posicion = 0;
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findByNextLibreta($posicion);
Then in LibretaRepository.php
public function findByNextLibreta($posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin('l.caja', 'c')
->where('l.vendedor is NULL')
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
It differs a little cuz didn't know how to pass the NULL value Julien was proposing so I used l.vendedor is NULL burned in the code.