Issue when trying to use doctrine queryBuilder - php

I have two entities Categorie and ChampCat with ManyToMany relation and I want to get list of categories with related ChampCat by using doctrine QueryBuilder so I have used this query:
class CategorieRepository extends \Doctrine\ORM\EntityRepository
{
public function myFindCategories(array $tab){
$em = $this->getEntityManager();
$query = $em->select(array('cat', 'ch'))
->from('AnnonceBundle\Entity\Categorie', 'cat')
->join('cat.champsCat', 'ch')
->where('cat.id In (:tabOfIds)')
->setParameter('tabOfIds', array_values($tab))
->getQuery();
return $query->getResult();
}
}
Here u can see the Categorie Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\CategorieRepository")
*/
class Categorie implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="refCat", type="string", length=100)
*/
private $refCat;
/**
* #var string
*
* #ORM\Column(name="libelleCat", type="string", length=50)
*/
private $libelleCat;
/**
* #ORM\ManyToMany(targetEntity="AnnonceBundle\Entity\ChampCat",cascade={"persist"})
*/
private $champsCat;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set refCat
*
* #param string $refCat
*
* #return Categorie
*/
public function setRefCat($refCat)
{
$this->refCat = $refCat;
return $this;
}
/**
* Get refCat
*
* #return string
*/
public function getRefCat()
{
return $this->refCat;
}
/**
* Set libelleCat
*
* #param string $libelleCat
*
* #return Categorie
*/
public function setLibelleCat($libelleCat)
{
$this->libelleCat = $libelleCat;
return $this;
}
/**
* Get libelleCat
*
* #return string
*/
public function getLibelleCat()
{
return $this->libelleCat;
}
/**
* Set champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function setChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat = null)
{
$this->champsCat = $champsCat;
return $this;
}
/**
* Get champsCat
*
* #return \AnnonceBundle\Entity\ChampCat
*/
public function getChampsCat()
{
return $this->champsCat;
}
/**
* Constructor
*/
public function __construct()
{
$this->champsCat = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function addChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat[] = $champsCat;
return $this;
}
/**
* Remove champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*/
public function removeChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat->removeElement($champsCat);
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
And this is ChamCat Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ChampCat
*
* #ORM\Table(name="champ_cat")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\ChampCatRepository")
*/
class ChampCat implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*#var string
*
* #ORM\Column(name="refCh", type="string")
*/
private $refCh;
/**
* #var string
*
* #ORM\Column(name="nom_ch", type="string", length=255)
*/
private $nomCh;
/**
* #var bool
*
* #ORM\Column(name="app_ch", type="boolean")
*/
private $appCh;
/**
* #var string
*
* #ORM\Column(name="format_ch", type="string", length=255)
*/
private $formatCh;
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->refCh;
}
/**
* Set refCh
*
* #param integer $refCh
* #return ChampCat
*/
public function setRefCh($refCh)
{
$this->refCh = $refCh;
return $this;
}
/**
* Get refCh
*
* #return integer
*/
public function getRefCh()
{
return $this->refCh;
}
/**
* Set nomCh
*
* #param string $nomCh
* #return ChampCat
*/
public function setNomCh($nomCh)
{
$this->nomCh = $nomCh;
return $this;
}
/**
* Get nomCh
*
* #return string
*/
public function getNomCh()
{
return $this->nomCh;
}
/**
* Set appCh
*
* #param boolean $appCh
* #return ChampCat
*/
public function setAppCh($appCh)
{
$this->appCh = $appCh;
return $this;
}
/**
* Get appCh
*
* #return boolean
*/
public function getAppCh()
{
return $this->appCh;
}
/**
* Set formatCh
*
* #param string $formatCh
* #return ChampCat
*/
public function setFormatCh($formatCh)
{
$this->formatCh = $formatCh;
return $this;
}
/**
* Get formatCh
*
* #return string
*/
public function getFormatCh()
{
return $this->formatCh;
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
Unfortunately this query didn't work, so what am I missing ?

Is it working with this syntax?
public function myFindCategories(array $tab){
if(count($tab) == 0) return []; //or IN() will bug with an empty array
$query = $this->createQueryBuilder('cat')
->addSelect('ch')
->innerJoin('cat.champsCat', 'ch')
->where('cat.id in (:tabOfIds)')
->setParameter('tabOfIds', $tab)
->getQuery();
return $query->getResult();
}

Related

How to get categories and corresponding item count with one DQL query

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.

Symfony2 / Doctrine, A new entity was found through the relationship

trying to fix this over 48 hours. I have an entity BookingRequest.php which content is:
<?php
namespace Kutiwa\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BookingRequest
*
* #ORM\Table(name="booking_request")
* #ORM\Entity(repositoryClass="Kutiwa\PlatformBundle\Repository\BookingRequestRepository")
*/
class BookingRequest
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=255, unique=true)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="arrival", type="string", length=255)
*/
private $arrival;
/**
* #var string
*
* #ORM\Column(name="departure", type="string", length=255)
*/
private $departure;
/**
* #var string
*
* #ORM\Column(name="requestDate", type="string", length=255)
*/
private $requestDate;
/**
* #var int
*
* #ORM\Column(name="rooms", type="integer")
*/
private $rooms;
/**
* #var string
*
* #ORM\Column(name="minPricing", type="string", length=255)
*/
private $minPricing;
/**
* #var string
*
* #ORM\Column(name="maxPricing", type="string", length=255)
*/
private $maxPricing;
/**
* #var string
*
* #ORM\Column(name="customerName", type="string", length=255)
*/
private $customerName;
/**
* #var string
*
* #ORM\Column(name="customerEmail", type="string", length=255, nullable=true)
*/
private $customerEmail;
/**
* #var string
*
* #ORM\Column(name="customerPhone", type="string", length=255)
*/
private $customerPhone;
/**
* #ORM\ManyToOne(targetEntity="Kutiwa\PlatformBundle\Entity\City")
* #ORM\JoinColumn(nullable=false)
*/
private $destinationCity;
/**
* #ORM\ManyToOne(targetEntity="Kutiwa\PlatformBundle\Entity\City")
* #ORM\JoinColumn(nullable=false)
*/
private $customerCity;
/**
* #ORM\OneToOne(targetEntity="Kutiwa\PlatformBundle\Entity\MissionConfig", cascade={"persist"})
*/
private $missionConfig;
/**
* #ORM\OneToOne(targetEntity="Kutiwa\PlatformBundle\Entity\TourismConfig", cascade={"persist"})
*/
private $tourismConfig;
/**
* #ORM\OneToMany(targetEntity="Kutiwa\PlatformBundle\Entity\RoomsConfig", mappedBy="bookingRequest")
*/
private $roomsConfigs;
public function __construct() {
$this->setRequestDate(date("d/m/Y"));
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* #param string $code
*
* #return BookingRequest
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set arrival
*
* #param string $arrival
*
* #return BookingRequest
*/
public function setArrival($arrival)
{
$this->arrival = $arrival;
return $this;
}
/**
* Get arrival
*
* #return string
*/
public function getArrival()
{
return $this->arrival;
}
/**
* Set departure
*
* #param string $departure
*
* #return BookingRequest
*/
public function setDeparture($departure)
{
$this->departure = $departure;
return $this;
}
/**
* Get departure
*
* #return string
*/
public function getDeparture()
{
return $this->departure;
}
/**
* Set requestDate
*
* #param string $requestDate
*
* #return BookingRequest
*/
public function setRequestDate($requestDate)
{
$this->requestDate = $requestDate;
return $this;
}
/**
* Get requestDate
*
* #return string
*/
public function getRequestDate()
{
return $this->requestDate;
}
/**
* Set rooms
*
* #param integer $rooms
*
* #return BookingRequest
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
return $this;
}
/**
* Get rooms
*
* #return integer
*/
public function getRooms()
{
return $this->rooms;
}
/**
* Set minPricing
*
* #param string $minPricing
*
* #return BookingRequest
*/
public function setMinPricing($minPricing)
{
$this->minPricing = $minPricing;
return $this;
}
/**
* Get minPricing
*
* #return string
*/
public function getMinPricing()
{
return $this->minPricing;
}
/**
* Set maxPricing
*
* #param string $maxPricing
*
* #return BookingRequest
*/
public function setMaxPricing($maxPricing)
{
$this->maxPricing = $maxPricing;
return $this;
}
/**
* Get maxPricing
*
* #return string
*/
public function getMaxPricing()
{
return $this->maxPricing;
}
/**
* Set customerName
*
* #param string $customerName
*
* #return BookingRequest
*/
public function setCustomerName($customerName)
{
$this->customerName = $customerName;
return $this;
}
/**
* Get customerName
*
* #return string
*/
public function getCustomerName()
{
return $this->customerName;
}
/**
* Set customerEmail
*
* #param string $customerEmail
*
* #return BookingRequest
*/
public function setCustomerEmail($customerEmail)
{
$this->customerEmail = $customerEmail;
return $this;
}
/**
* Get customerEmail
*
* #return string
*/
public function getCustomerEmail()
{
return $this->customerEmail;
}
/**
* Set customerPhone
*
* #param string $customerPhone
*
* #return BookingRequest
*/
public function setCustomerPhone($customerPhone)
{
$this->customerPhone = $customerPhone;
return $this;
}
/**
* Get customerPhone
*
* #return string
*/
public function getCustomerPhone()
{
return $this->customerPhone;
}
/**
* Set destinationCity
*
* #param \Kutiwa\PlatformBundle\Entity\City $destinationCity
*
* #return BookingRequest
*/
public function setDestinationCity(\Kutiwa\PlatformBundle\Entity\City $destinationCity)
{
$this->destinationCity = $destinationCity;
return $this;
}
/**
* Get destinationCity
*
* #return \Kutiwa\PlatformBundle\Entity\City
*/
public function getDestinationCity()
{
return $this->destinationCity;
}
/**
* Set customerCity
*
* #param \Kutiwa\PlatformBundle\Entity\City $customerCity
*
* #return BookingRequest
*/
public function setCustomerCity(\Kutiwa\PlatformBundle\Entity\City $customerCity)
{
$this->customerCity = $customerCity;
return $this;
}
/**
* Get customerCity
*
* #return \Kutiwa\PlatformBundle\Entity\City
*/
public function getCustomerCity()
{
return $this->customerCity;
}
/**
* Set missionConfig
*
* #param \Kutiwa\PlatformBundle\Entity\MissionConfig $missionConfig
*
* #return BookingRequest
*/
public function setMissionConfig(\Kutiwa\PlatformBundle\Entity\MissionConfig $missionConfig = null)
{
$this->missionConfig = $missionConfig;
return $this;
}
/**
* Get missionConfig
*
* #return \Kutiwa\PlatformBundle\Entity\MissionConfig
*/
public function getMissionConfig()
{
return $this->missionConfig;
}
/**
* Set tourismConfig
*
* #param \Kutiwa\PlatformBundle\Entity\TourismConfig $tourismConfig
*
* #return BookingRequest
*/
public function setTourismConfig(\Kutiwa\PlatformBundle\Entity\TourismConfig $tourismConfig = null)
{
$this->tourismConfig = $tourismConfig;
return $this;
}
/**
* Get tourismConfig
*
* #return \Kutiwa\PlatformBundle\Entity\TourismConfig
*/
public function getTourismConfig()
{
return $this->tourismConfig;
}
/**
* Add roomsConfig
*
* #param \Kutiwa\PlatformBundle\Entity\RoomsConfig $roomsConfig
*
* #return BookingRequest
*/
public function addRoomsConfig(\Kutiwa\PlatformBundle\Entity\RoomsConfig $roomsConfig)
{
$this->roomsConfigs[] = $roomsConfig;
return $this;
}
/**
* Remove roomsConfig
*
* #param \Kutiwa\PlatformBundle\Entity\RoomsConfig $roomsConfig
*/
public function removeRoomsConfig(\Kutiwa\PlatformBundle\Entity\RoomsConfig $roomsConfig)
{
$this->roomsConfigs->removeElement($roomsConfig);
}
/**
* Get roomsConfigs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoomsConfigs()
{
return $this->roomsConfigs;
}
}
and another entity RoomsConfig.php
<?php
namespace Kutiwa\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RoomsConfig
*
* #ORM\Table(name="rooms_config")
* #ORM\Entity(repositoryClass="Kutiwa\PlatformBundle\Repository\RoomsConfigRepository")
*/
class RoomsConfig
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var bool
*
* #ORM\Column(name="airConditionner", type="boolean")
*/
private $airConditionner;
/**
* #var bool
*
* #ORM\Column(name="wifi", type="boolean")
*/
private $wifi;
/**
* #var bool
*
* #ORM\Column(name="balcony", type="boolean")
*/
private $balcony;
/**
* #var string
*
* #ORM\Column(name="tv", type="boolean")
*/
private $tv;
/**
* #ORM\ManyToOne(targetEntity="Kutiwa\PlatformBundle\Entity\BookingRequest", inversedBy="roomsConfigs", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $bookingRequest;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set airConditionner
*
* #param boolean $airConditionner
*
* #return RoomsConfig
*/
public function setAirConditionner($airConditionner)
{
$this->airConditionner = $airConditionner;
return $this;
}
/**
* Get airConditionner
*
* #return boolean
*/
public function getAirConditionner()
{
return $this->airConditionner;
}
/**
* Set wifi
*
* #param boolean $wifi
*
* #return RoomsConfig
*/
public function setWifi($wifi)
{
$this->wifi = $wifi;
return $this;
}
/**
* Get wifi
*
* #return boolean
*/
public function getWifi()
{
return $this->wifi;
}
/**
* Set balcony
*
* #param boolean $balcony
*
* #return RoomsConfig
*/
public function setBalcony($balcony)
{
$this->balcony = $balcony;
return $this;
}
/**
* Get balcony
*
* #return boolean
*/
public function getBalcony()
{
return $this->balcony;
}
/**
* Set tv
*
* #param boolean $tv
*
* #return RoomsConfig
*/
public function setTv($tv)
{
$this->tv = $tv;
return $this;
}
/**
* Get tv
*
* #return boolean
*/
public function getTv()
{
return $this->tv;
}
/**
* Set bookingRequest
*
* #param \Kutiwa\PlatformBundle\Entity\BookingRequest $bookingRequest
*
* #return RoomsConfig
*/
public function setBookingRequest(\Kutiwa\PlatformBundle\Entity\BookingRequest $bookingRequest)
{
$this->bookingRequest = $bookingRequest;
$bookingRequest->addRoomsConfig($this);
return $this;
}
/**
* Get bookingRequest
*
* #return \Kutiwa\PlatformBundle\Entity\BookingRequest
*/
public function getBookingRequest()
{
return $this->bookingRequest;
}
}
The problem is, when I try to persist a RoomsConfig entity, I got an error
A new entity was found through the relationship
'Kutiwa\PlatformBundle\Entity\BookingRequest#destinationCity' that was
not configured to cascade persist operations for entity: TIKO. To
solve this issue: Either explicitly call EntityManager#persist() on
this unknown entity or configure cascade persist this association in
the mapping for example #ManyToOne(..,cascade={"persist"})
I don't need a cascade effect on City and BookingRequest relation, here is my BookingRequestType.php
<?php
namespace Kutiwa\PlatformBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BookingRequestType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('arrival', TextType::class)
->add('departure', TextType::class)
->add('rooms', IntegerType::class)
->add('customerName', TextType::class)
->add('customerEmail', TextType::class, array('required' => false))
->add('customerPhone', TextType::class)
->add('destinationCity', EntityType::class, array(
'choice_label' => 'name',
'class' => 'KutiwaPlatformBundle:City'
))
->add('customerCity', EntityType::class, array(
'choice_label' => 'name',
'class' => 'KutiwaPlatformBundle:City'
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kutiwa\PlatformBundle\Entity\BookingRequest'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'kutiwa_platformbundle_bookingrequest';
}
}
If I try to persist only BookingRequest entity, there is no problem, but when I persist RoomsConfig entity, I got that error. Help please. Thks.
Before persist your RoomsConfig, try to use findOneBy to find BookingRequest, or whatever you use to find the entity, and then set the found entity with setBookingRequest.

Doctrine2: how to get one of the inversed side entities with ManyToOne relationship for a given id

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;
}
}

Order by an specific related field with doctrine2 findoneby functionality

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.

Symfony2 - Doctrine exception: class used in the discriminator map does not exist

I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.

Categories