I have a problem with a query in doctrine i started using Symfony recently for to be continued a old project in Symfony and now i want learn it.
I start to explain from db and i write only the fields that interest me :
user(id,name,surname,phat)
user_reference(id,id_user[FOREIGN KEY id FROM user],id_user_referenced[FOREIGN KEY id FROM user])
This is the query :
$id_user = $user->getId();
$query = $em->createQueryBuilder()
->select('ur','uu')
->from('DtEcBundle:UserReferences', 'ur')
->innerJoin("ur.id_user","uu")
->where("ur.id_user = :id_user")
->setParameter("id_user",$id_user)
->getQuery();
$userpyramid = $query->getResult();
I print in my twig file id_user_referenced but i would print too "name, surname and path" from USER table
For print id_user_referenced in the Entity UserReferences there is this code:
/**
* Set id_user_referenced
*
* #param \Dt\EcBundle\Entity\User $idUserReferenced
* #return UserReferences
*/
public function setIdUserReferenced(\Dt\EcBundle\Entity\User $idUserReferenced = null) {
$this->id_user_referenced = $idUserReferenced;
return $this;
}
/**
* Get id_user_referenced
*
* #return \Dt\EcBundle\Entity\User
*/
public function getIdUserReferenced() {
return $this->id_user_referenced;
}
Transform a number like id to string in Entity User with:
public function __toString(){
return strval($this->id);
}
Now if i add to my query in the select this:
->select('ur','uu.path')
Symfony send me an error:
Key "idUserReferenced" for array with keys "0, path" does not exist in
DtEcBundle:Profilo:digitalpr-profile.html.twig at line 40
Why?? How can i solved it??
UserReferences.php
namespace Dt\EcBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* UserReferences
*
* #ORM\Table(name="user_references" ,uniqueConstraints= {#ORM\UniqueConstraint(name="recension_unique", columns={"id_user", "id_user_referenced"})})
* #ORM\Entity(repositoryClass="Dt\EcBundle\Entity\UserReferencesRepository")
*/ class UserReferences {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #var Dt\EcBundle\Entity\User
* #ORM\ManyToOne(targetEntity="Dt\EcBundle\Entity\User", inversedBy="references")
* #ORM\JoinColumn(name="id_user", referencedColumnName="id")
*/
private $id_user;
/**
* #ORM\ManyToOne(targetEntity="Dt\EcBundle\Entity\User")
* #ORM\JoinColumn(name="id_user_referenced", referencedColumnName="id")
* */
private $id_user_referenced;
/**
*
* #var string
* #ORM\Column(name="reference", type="text", nullable=false,unique=false);
*/
private $reference;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set reference
*
* #param string $reference
* #return UserReferences
*/
public function setReference($reference) {
$this->reference = $reference;
return $this;
}
/**
* Get reference
*
* #return string
*/
public function getReference() {
return $this->reference;
}
/**
* Set id_user
*
* #param \Dt\EcBundle\Entity\User $idUser
* #return UserReferences
*/
public function setIdUser(\Dt\EcBundle\Entity\User $idUser = null) {
$this->id_user = $idUser;
return $this;
}
/**
* Get id_user
*
* #return \Dt\EcBundle\Entity\User
*/
public function getIdUser() {
return $this->id_user;
}
/**
* Set id_user_referenced
*
* #param \Dt\EcBundle\Entity\User $idUserReferenced
* #return UserReferences
*/
public function setIdUserReferenced(\Dt\EcBundle\Entity\User $idUserReferenced = null) {
$this->id_user_referenced = $idUserReferenced;
return $this;
}
/**
* Get id_user_referenced
*
* #return \Dt\EcBundle\Entity\User
*/
public function getIdUserReferenced() {
return $this->id_user_referenced;
}
}
User.php
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, unique=false, nullable=false)
* #Assert\NotBlank(message="user.name.not.blank")
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.name.not.min",
* maxMessage="user.name.not.max" )
*/
protected $name;
/**
* #var string
*
* #ORM\Column(name="surname", type="string", length=255, unique=false, nullable=false)
* #Assert\NotBlank(message="user.surname.not.blank")
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.surname.not.min",
* maxMessage="user.surname.not.max" )
*/
protected $surname;
/**
* #var \DateTime
* #ORM\Column(name="borndate", type="datetime",unique=false,nullable=false)
*/
protected $borndate;
/**
*
* #var string
* #ORM\Column(name="tel", type="string",length=50, unique=true,nullable=true)
* #Assert\Regex("/[0-9]/")
*/
protected $tel;
/**
*
* #var string
* #ORM\Column(name="city", type="string",length=255,unique=false,nullable=true)
* #Assert\NotBlank(message="user.expert.city.not.blank",groups={"Expert"})
* #Assert\NotBlank(message="user.expert.city.not.blank",groups={"ExpertProfile"})
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.expert.city.not.min",
* maxMessage="user.expert.city.not.max", groups={"Expert"} )
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.expert.city.not.min",
* maxMessage="user.expert.city.not.max", groups={"ExpertProfile"} )
*/
protected $city;
/**
*
* #var string
* #ORM\Column(name="street", type="string",length=255,unique=false,nullable=true)
* #Assert\NotBlank(message="user.expert.street.not.blank",groups={"Expert"})
* #Assert\NotBlank(message="user.expert.street.not.blank",groups={"ExpertProfile"})
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.expert.street.not.min",
* maxMessage="user.expert.street.not.max", groups={"Expert"} )
* #Assert\Length(
* min=2,
* max=150,
* minMessage="user.expert.street.not.min",
* maxMessage="user.expert.street.not.max", groups={"ExpertProfile"} )
*/
protected $street;
/**
*
* #var type
*
* #Assert\File(
* maxSize = "1024k",
* mimeTypes = {"image/gif","image/jpeg","image/pjpeg","image/png"},
* mimeTypesMessage = "user.image.mimetypes",
* maxSizeMessage = "user.image.maxsize"
* )
* #Assert\NotBlank(message="user.expert.mandatory.photo",groups={"Expert"})
*
*/
protected $photo;
/**
* #ORM\Column(name="photo_path",type="string", length=255, nullable=true,unique=true)
*/
protected $path;
/**
* Membri per la gestione dei file
*
*/
The problem is that doctrine hydrates your result in Array Hydration mode, while you expect Object Hydraion.
In the first case you ask for 2 related objects and doctrine can link them. In the second you ask for an object and for a scalar value, and doctrine cannot link them, so it returns them in two separate fields of an result array.
So the result that you have got from $query->getResult() in case of select('ur','uu.path') is not an array of User objects, but an array of 2 fields - $result[0] where you have all found User objects, and $result['path'] for uu.path - because uu.path is scalar value rather than object.
So you need to make select('ur','uu') and address your result as $result->getIdUserReferenced()->getPath().
Or (if you want to save some resources, but I don't think it worth it) make select('ur','uu.path') and then make var_dump of result. And you will see how to address to what you need.
I try in this mode but is not good
$id_user = $user->getId();
$query = $em->createQueryBuilder()
->select('ur','uu')
->from('DtEcBundle:UserReferences', 'ur')
->innerJoin("ur.id_user","uu")
->where("ur.id_user = :id_user")
->setParameter("id_user",$id_user)
->getQuery();
$userpyramid = $query->getResult();
$form = $this->get('form.factory')->createNamedBuilder('form', 'form')
->setMethod('POST')
->setAction($this->generateUrl('profilo_secondlevel'))
->add('save', 'submit', ['label' => 'Prova'])
->getForm();*/
$result->getIdUserReferenced()->getPath();
return $this->render('DtEcBundle:Profilo:index.html.twig', array(
'user' => $user,
'tags' => $tags,
'followers' =>$followers,
'expert' =>$expert,
'user_expert' =>$user_expert,
'well_cat' =>$well_cat,
'user_notification' => $user_notifications,
"udputenti" => $udputenti,
"userpyramid" => $userpyramid,
"result"=> $result
//'form'=>$form->createView()
));`
Related
I am building a shipping system for an eCommerce site using doctrine. To do this I have get the appropriate shipping methods and prices based on product and region data in the checkout.
I am using the following code with the QueryBuilder:
$shippingPriceReccords
= $this->em->createQueryBuilder()
->select('price')
->from('OrderShippingPrice', 'price')
->innerJoin('OrderShippingMethod', 'method', 'price.fkOrderShippingMethod = method.id')
->innerJoin('OrderShippingMethodRegionMapping', 'map', 'map.fkOrderShippingMethod = method.id')
->where('price.fkProductType = :fkProductType')
->andwhere('price.fkBrand = :fkBrand')
->andwhere('map.fkRegion = :fkRegion')
->setParameters([
'fkProductType' => $fkProductType,
'fkBrand' => $fkBrand,
'fkRegion' => $regionID,
])
->getQuery()
->setFetchMode("OrderCart", "address", \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER)
->getResult();
But this is failing and giving me this error:
[Syntax Error] line 0, col 87: Error: Expected Literal, got 'JOIN'
The DQL from the above query:
SELECT price FROM OrderShippingPrice price INNER JOIN OrderShippingMethod method INNER JOIN OrderShippingMethodRegionMapping map WHERE price.fkProductType = :fkProductType AND price.fkBrand = :fkBrand AND map.fkRegion = :fkRegion
OrderShippingPrice contains:
<?php
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* OrderShippingPrice
*
* #ORM\Table(name="orderShippingPrice")
* #ORM\Entity
*/
class OrderShippingPrice
{
/**
*
* Normal string / int object data
*
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="fkOrderShippingMethod", type="integer", nullable=true)
*/
private $fkOrderShippingMethod = '0';
/**
* #var float
*
* #ORM\Column(name="price", type="float", precision=7, scale=2, nullable=false)
*/
private $price = '0.00';
/**
* #var int
*
* #ORM\Column(name="fkProductType", type="integer", nullable=true)
*/
private $fkProductType = '0';
/**
* #var int
*
* #ORM\Column(name="fkBrand", type="integer", nullable=true)
*/
private $fkBrand = '0';
/**
* #var string
*
* #ORM\Column(name="isExpeditable", type="string", length=16, nullable=false)
*/
private $isExpeditable = '0';
/**
* #var string
*
* #ORM\Column(name="expediteDescription", type="text", length=65535, nullable=false)
*/
private $expediteDescription = '';
/**
* #var string
*
* #ORM\Column(name="showLiftGateOption", type="string", length=16, nullable=false)
*/
private $showLiftGateOption = '0';
/**
* #var string
*
* #ORM\Column(name="showDestinationOption", type="string", length=16, nullable=false)
*/
private $showDestinationOption = '0';
/**
* #var string
*
* #ORM\Column(name="productNotAvailable", type="string", length=16, nullable=false)
*/
private $productNotAvailable = '0';
/**
*
* Relationship managment propperties
*
*/
/**
* Many OrderShippingPrices have One OrderShippingMethod.
* #ORM\ManyToOne(targetEntity="OrderShippingMethod", fetch="EAGER")
* #ORM\JoinColumn(name="fkOrderShippingMethod", referencedColumnName="id")
**/
private $orderShippingMethod;
/**
* Get orderOrderShippingMethod
*
* #return OrderShippingMethod
*/
public function getOrderShippingMethod()
{
return $this->orderShippingMethod;
}
/**
*
* Normal string / int getters and setters
*
*/
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set fkOrderShippingMethod
*
* #param string $fkOrderShippingMethod
*
* #return OrderCart
*/
public function setFkOrderShippingMethod($fkOrderShippingMethod)
{
$this->fkOrderShippingMethod = $fkOrderShippingMethod;
return $this;
}
/**
* Get fkOrderShippingMethod
*
* #return string
*/
public function getFkOrderShippingMethod()
{
return $this->fkOrderShippingMethod;
}
/**
* Set price
*
* #param string $price
*
* #return OrderCart
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set fkProductType
*
* #param string $fkProductType
*
* #return OrderCart
*/
public function setFkProductType($fkProductType)
{
$this->fkProductType = $fkProductType;
return $this;
}
/**
* Get fkProductType
*
* #return string
*/
public function getFkProductType()
{
return $this->fkProductType;
}
/**
* Set fkBrand
*
* #param string $fkBrand
*
* #return OrderCart
*/
public function setFkBrand($fkBrand)
{
$this->fkBrand = $fkBrand;
return $this;
}
/**
* Get fkBrand
*
* #return string
*/
public function getFkBrand()
{
return $this->fkBrand;
}
/**
* Set isExpeditable
*
* #param string $isExpeditable
*
* #return OrderCart
*/
public function setIsExpeditable($isExpeditable)
{
$this->isExpeditable = $isExpeditable;
return $this;
}
/**
* Get isExpeditable
*
* #return string
*/
public function getIsExpeditable()
{
return $this->isExpeditable;
}
/**
* Set expediteDescription
*
* #param string $expediteDescription
*
* #return OrderCart
*/
public function setExpediteDescription($expediteDescription)
{
$this->expediteDescription = $expediteDescription;
return $this;
}
/**
* Get expediteDescription
*
* #return string
*/
public function getExpediteDescription()
{
return $this->expediteDescription;
}
/**
* Set showLiftGateOption
*
* #param string $showLiftGateOption
*
* #return OrderCart
*/
public function setShowLiftGateOption($showLiftGateOption)
{
$this->showLiftGateOption = $showLiftGateOption;
return $this;
}
/**
* Get showLiftGateOption
*
* #return string
*/
public function getShowLiftGateOption()
{
return $this->showLiftGateOption;
}
/**
* Set showDestinationOption
*
* #param string $showDestinationOption
*
* #return OrderCart
*/
public function setShowDestinationOption($showDestinationOption)
{
$this->showDestinationOption = $showDestinationOption;
return $this;
}
/**
* Get showDestinationOption
*
* #return string
*/
public function getShowDestinationOption()
{
return $this->showDestinationOption;
}
/**
* Set productNotAvailable
*
* #param string $productNotAvailable
*
* #return OrderCart
*/
public function setProductNotAvailable($productNotAvailable)
{
$this->productNotAvailable = $productNotAvailable;
return $this;
}
/**
* Get productNotAvailable
*
* #return string
*/
public function getProductNotAvailable()
{
return $this->productNotAvailable;
}
}
OrderShippingMethod contains:
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* OrderShippingMethod
*
* #ORM\Table(name="orderShippingMethod")
* #ORM\Entity
*/
class OrderShippingMethod
{
/**
*
* Normal string / int object data
*
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="text", length=255, nullable=false)
*/
private $name = '';
/**
* #var string
*
* #ORM\Column(name="carrier", type="string", length=32, nullable=false)
*/
private $carrier = '';
/**
* #var string
*
* #ORM\Column(name="bvCode", type="string", length=32, nullable=false)
*/
private $bvCode = '';
/**
* #var string
*
* #ORM\Column(name="trackingUrl", type="string", length=255, nullable=true)
*/
private $trackingUrl = '';
/**
* #var int
*
* #ORM\Column(name="minimumLeadTime", type="integer", nullable=false)
*/
private $minimumLeadTime = '0';
/**
* #var int
*
* #ORM\Column(name="maximumLeadTime", type="integer", nullable=false)
*/
private $maximumLeadTime = '0';
/**
*
* Relationship managment propperties
*
*/
/**
* #ORM\OneToMany(targetEntity="OrderShippingMethodRegionMapping", mappedBy="orderShippingMethod", cascade={"persist", "remove"}, orphanRemoval=true, fetch="EAGER")
* #var orderShippingMethodRegionMappings[]
**/
public $orderShippingMethodRegionMappings;
/**
* Constructor
*
* Create array for collection of orderShippingMethodRegionMappings
*/
public function __construct()
{
$this->orderShippingMethodRegionMappings = new ArrayCollection();
}
/**
* Get orderShippingMethodRegionMapping(s)
*
* #return array
*/
public function getOrderShippingMethodRegionMappings()
{
return $this->orderShippingMethodRegionMappings;
}
/**
*
* Normal string / int getters and setters
*
*/
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param int $name
*
* #return OrderCart
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return int
*/
public function getName()
{
return $this->name;
}
/**
* Set carrier
*
* #param string $carrier
*
* #return OrderCart
*/
public function setCarrier($carrier)
{
$this->carrier = $carrier;
return $this;
}
/**
* Get carrier
*
* #return string
*/
public function getCarrier()
{
return $this->carrier;
}
/**
* Set bvCode
*
* #param string $bvCode
*
* #return OrderCart
*/
public function setBvCode($bvCode)
{
$this->bvCode = $bvCode;
return $this;
}
/**
* Get bvCode
*
* #return string
*/
public function getBvCode()
{
return $this->bvCode;
}
/**
* Set trackingUrl
*
* #param string $trackingUrl
*
* #return OrderCart
*/
public function setTrackingUrl($trackingUrl)
{
$this->trackingUrl = $trackingUrl;
return $this;
}
/**
* Get trackingUrl
*
* #return string
*/
public function getTrackingUrl()
{
return $this->trackingUrl;
}
/**
* Set minimumLeadTime
*
* #param string $minimumLeadTime
*
* #return OrderCart
*/
public function setMinimumLeadTime($minimumLeadTime)
{
$this->minimumLeadTime = $minimumLeadTime;
return $this;
}
/**
* Get minimumLeadTime
*
* #return string
*/
public function getMinimumLeadTime()
{
return $this->minimumLeadTime;
}
/**
* Set maximumLeadTime
*
* #param string $maximumLeadTime
*
* #return OrderCart
*/
public function setMaximumLeadTime($maximumLeadTime)
{
$this->maximumLeadTime = $maximumLeadTime;
return $this;
}
/**
* Get maximumLeadTime
*
* #return string
*/
public function getMaximumLeadTime()
{
return $this->maximumLeadTime;
}
}
OrderShippingMethodRegionMapping contains:
<?php
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* OrderShippingMethodRegionMapping
*
* #ORM\Table(name="orderShippingMethodRegionMapping")
* #ORM\Entity
*/
class OrderShippingMethodRegionMapping
{
/**
*
* Normal string / int object data
*
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="fkOrderShippingMethod", type="integer")
*/
private $fkOrderShippingMethod = '0';
/**
* #var int
*
* #ORM\Column(name="fkOrderRegion", type="integer")
*/
private $fkOrderRegion = '0';
/**
*
* Relationship managment propperties
*
*/
/**
* Many OrderShippingPrices have One OrderShippingMethod.
* #ORM\ManyToOne(targetEntity="OrderShippingMethod", inversedBy="orderShippingMethodRegionMappings")
* #ORM\JoinColumn(name="fkOrderShippingMethod", referencedColumnName="id")
**/
private $orderShippingMethod;
/**
* Sets a new OrderShippingMethod and cleans the previous one if set
* #param OrderShippingMethod
*/
public function setOrderShippingMethod(OrderShippingMethod $orderShippingMethod)
{
$this->orderShippingMethod = $orderShippingMethod;
}
/**
* Get orderOrderShippingMethod
*
* #return OrderShippingMethod
*/
public function getOrderShippingMethod()
{
return $this->orderShippingMethod;
}
/**
*
* Normal string / int getters and setters
*
*/
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set fkOrderShippingMethod
*
* #param int $fkOrderShippingMethod
*
* #return OrderCart
*/
public function setFkOrderShippingMethod($fkOrderShippingMethod)
{
$this->fkOrderShippingMethod = $fkOrderShippingMethod;
return $this;
}
/**
* Get fkOrderShippingMethod
*
* #return int
*/
public function getFkOrderShippingMethod()
{
return $this->fkOrderShippingMethod;
}
/**
* Set fkOrderRegion
*
* #param int $fkOrderRegion
*
* #return OrderCart
*/
public function setFkOrderRegion($fkOrderRegion)
{
$this->fkOrderRegion = $fkOrderRegion;
return $this;
}
/**
* Get fkOrderRegion
*
* #return int
*/
public function getFkOrderRegion()
{
return $this->fkOrderRegion;
}
}
Can someone tell me what I am doing wrong? Thanks for the help.
You are missing an argument in the innerJoin method call. You have to do this :
$shippingPriceReccords
= $this->em->createQueryBuilder()
->select('price')
->from('OrderShippingPrice', 'price')
->innerJoin('OrderShippingMethod', 'method', 'WITH', 'price.fkOrderShippingMethod = method.id')
->innerJoin('OrderShippingMethodRegionMapping', 'map', 'WITH', 'map.fkOrderShippingMethod = method.id')
->where('price.fkProductType = :fkProductType')
->andwhere('price.fkBrand = :fkBrand')
->andwhere('map.fkRegion = :fkRegion')
->setParameters([
'fkProductType' => $fkProductType,
'fkBrand' => $fkBrand,
'fkRegion' => $regionID,
])
->getQuery()
->setFetchMode("OrderCart", "address", \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER)
->getResult();
See the documentation :
// Example - $qb->innerJoin('u.Group', 'g', Expr\Join::WITH, $qb->expr()->eq('u.status_id', '?1'))
// Example - $qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1')
// Example - $qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id')
public function innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null);
what's the wrong in this code
i want to create query with multi join but unfortunately this error displayed
[this is my SearchController controller]
class SearchController extends Controller {
public function indexAction() {
$em = $this->get('doctrine.orm.entity_manager');
$users = $em
->createQueryBuilder('P')
->select('P.pname, Q.qname,P.gender,P.phone,P.yearsOfExperience,P.graduationYear,c.cname')
->add('from', 'serachBundle:Person P')
->Join('P.Qualification', 'Q')
->Join('Q.Category', 'c')
->where('P.qualificationId=Q.id')
->andwhere('Q.categoryId=c.id')
->getQuery();
$user = $users->getResult();
print_r($user);
//qualification
$Qlist = $this->getDoctrine()
->getRepository('serachBundle:qualification')
->findAll();
//category
$Catlist = $this->getDoctrine()
->getRepository('serachBundle:category')
->findAll();
return $this->render('serachBundle:Default:Search.html.twig', array('user' => $user, 'Qlist' => $Qlist, 'Catlist' => $Catlist));
}
this my person entity
<?php
namespace Search\serachBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Person
*
* #ORM\Table(name="person", indexes={#ORM\Index(name="companyId", columns={"companyId", "qualificationId"}), #ORM\Index(name="qualificationId", columns={"qualificationId"}), #ORM\Index(name="IDX_34DCD1762480E723", columns={"companyId"})})
* #ORM\Entity
*/
class Person
{
/**
* #var string
*
* #ORM\Column(name="pname", type="string", length=255, nullable=false)
*/
private $pname;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255, nullable=false)
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255, nullable=false)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="gender", type="string", length=255, nullable=false)
*/
private $gender;
/**
* #var integer
*
* #ORM\Column(name="yearsOfExperience", type="integer", nullable=false)
*/
private $yearsofexperience;
/**
* #var integer
*
* #ORM\Column(name="graduationYear", type="integer", nullable=false)
*/
private $graduationyear;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Search\serachBundle\Entity\Company
*
* #ORM\ManyToOne(targetEntity="Search\serachBundle\Entity\Company")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="companyId", referencedColumnName="id")
* })
*/
private $companyid;
/**
* #var \Search\serachBundle\Entity\Qualification
*
* #ORM\ManyToOne(targetEntity="Search\serachBundle\Entity\Qualification")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="qualificationId", referencedColumnName="id")
* })
*/
private $qualificationid;
/**
* Set pname
*
* #param string $pname
* #return Person
*/
public function setPname($pname)
{
$this->pname = $pname;
return $this;
}
/**
* Get pname
*
* #return string
*/
public function getPname()
{
return $this->pname;
}
/**
* Set address
*
* #param string $address
* #return Person
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set phone
*
* #param string $phone
* #return Person
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set gender
*
* #param string $gender
* #return Person
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set yearsofexperience
*
* #param integer $yearsofexperience
* #return Person
*/
public function setYearsofexperience($yearsofexperience)
{
$this->yearsofexperience = $yearsofexperience;
return $this;
}
/**
* Get yearsofexperience
*
* #return integer
*/
public function getYearsofexperience()
{
return $this->yearsofexperience;
}
/**
* Set graduationyear
*
* #param integer $graduationyear
* #return Person
*/
public function setGraduationyear($graduationyear)
{
$this->graduationyear = $graduationyear;
return $this;
}
/**
* Get graduationyear
*
* #return integer
*/
public function getGraduationyear()
{
return $this->graduationyear;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set companyid
*
* #param \Search\serachBundle\Entity\Company $companyid
* #return Person
*/
public function setCompanyid(\Search\serachBundle\Entity\Company $companyid = null)
{
$this->companyid = $companyid;
return $this;
}
/**
* Get companyid
*
* #return \Search\serachBundle\Entity\Company
*/
public function getCompanyid()
{
return $this->companyid;
}
/**
* Set qualificationid
*
* #param \Search\serachBundle\Entity\Qualification $qualificationid
* #return Person
*/
public function setQualificationid(\Search\serachBundle\Entity\Qualification $qualificationid = null)
{
$this->qualificationid = $qualificationid;
return $this;
}
/**
* Get qualificationid
*
* #return \Search\serachBundle\Entity\Qualification
*/
public function getQualificationid()
{
return $this->qualificationid;
}
}
(Entities are objects with identity. Their identity has a conceptual meaning inside your domain. In a CMS application each article has a unique id. You can uniquely identify each article by that id.)
this my Qualification entity
<?php
namespace Search\serachBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Qualification
*
* #ORM\Table(name="qualification", indexes={#ORM\Index(name="categoryId", columns={"categoryId"})})
* #ORM\Entity
*/
class Qualification
{
/**
* #var string
*
* #ORM\Column(name="qname", type="string", length=255, nullable=false)
*/
private $qname;
/**
* #var string
*
* #ORM\Column(name="specialty", type="string", length=255, nullable=false)
*/
private $specialty;
/**
* #var string
*
* #ORM\Column(name="qualifDesc", type="string", length=255, nullable=false)
*/
private $qualifdesc;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Search\serachBundle\Entity\Category
*
* #ORM\ManyToOne(targetEntity="Search\serachBundle\Entity\Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categoryId", referencedColumnName="id")
* })
*/
private $categoryid;
/**
* Set qname
*
* #param string $qname
* #return Qualification
*/
public function setQname($qname)
{
$this->qname = $qname;
return $this;
}
/**
* Get qname
*
* #return string
*/
public function getQname()
{
return $this->qname;
}
/**
* Set specialty
*
* #param string $specialty
* #return Qualification
*/
public function setSpecialty($specialty)
{
$this->specialty = $specialty;
return $this;
}
/**
* Get specialty
*
* #return string
*/
public function getSpecialty()
{
return $this->specialty;
}
/**
* Set qualifdesc
*
* #param string $qualifdesc
* #return Qualification
*/
public function setQualifdesc($qualifdesc)
{
$this->qualifdesc = $qualifdesc;
return $this;
}
/**
* Get qualifdesc
*
* #return string
*/
public function getQualifdesc()
{
return $this->qualifdesc;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set categoryid
*
* #param \Search\serachBundle\Entity\Category $categoryid
* #return Qualification
*/
public function setCategoryid(\Search\serachBundle\Entity\Category $categoryid = null)
{
$this->categoryid = $categoryid;
return $this;
}
/**
* Get categoryid
*
* #return \Search\serachBundle\Entity\Category
*/
public function getCategoryid()
{
return $this->categoryid;
}
}
Thanks in advance if anyone can solve this. It would be a really great help
You named the relations as $qualificationid, so you should make your query something like this:
->Join('P.qualificationid', 'Q')
->Join('Q.categoryid', 'c')
Remember to make all queries inside repositories classes. And please, try to rename your bundle from serach to search :-D
The findAll() finds one result in my repository:
$retorno[] = $bd->getEntityManager()->getRepository($classname)->findAll();
Class of entity:
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* Subtipo
*
* #ORM\Table(name="subtipo", indexes={#ORM\Index(name="fk_Subtipo_Tipo1_idx", columns={"Tipo_id"})})
* #ORM\Entity
*/
class Subtipo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nome", type="string", length=45, nullable=false)
*/
private $nome;
/**
* #var \Tipo
*
* #ORM\ManyToOne(targetEntity="Tipo")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Tipo_id", referencedColumnName="id")
* })
*/
private $tipo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nome
*
* #param string $nome
*
* #return Subtipo
*/
public function setNome($nome)
{
$this->nome = $nome;
return $this;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
/**
* Set tipo
*
* #param \Tipo $tipo
*
* #return Subtipo
*/
public function setTipo(\Tipo $tipo = null)
{
$this->tipo = $tipo;
return $this;
}
/**
* Get tipo
*
* #return \Tipo
*/
public function getTipo()
{
return $this->tipo;
}
}
Somebody can help?
If you do this
$retorno[] = $bd->getEntityManager()->getRepository($classname)->findAll();
^----- this
You're creating an array of arrays (or array of ArrayCollection) so, if you inspect length of $retorno[] this will result in 1 element that will contain real results.
Something like
$retorno = [
0 => [
0 => 'first real result',
1 => 'second real result',
[...]
n => 'nth real result'
]
];
Just use this syntax
$retorno = $bd->getEntityManager()->getRepository($classname)->findAll();
(I'm a beginner)
I would like to automatically generate methods for related models (OneToMany and ManyToOne). Im doing it following docs http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
I added following properties and annotations to the models (I give here only two classes related by ManyToOne as a example) and run generate:doctrine:entities command with no errors and no results. I expected methods like __construct and addXXX() in Kategoria class with OnoToMany relation.
This is fragment I added to Kategoria class.
/**
* #ORM\OneToMany(targetEntity="Ksiazka", mappedBy="kategoria")
*/
protected $ksiazki;
This is entire Kategoria class with OneToMany relation.
#Kategoria.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Kategoria
*
* #ORM\Table(name="kategoria")
* #ORM\Entity
*/
class Kategoria
{
/**
* #var string
*
* #ORM\Column(name="nazwa", type="string", length=45, nullable=true)
*/
private $nazwa;
/**
* #var integer
*
* #ORM\Column(name="idKategoria", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idkategoria;
#THESE NEXT 4 LINES I ADDED
/**
* #ORM\OneToMany(targetEntity="Ksiazka", mappedBy="kategoria")
*/
protected $ksiazki;
/**
* Set nazwa
*
* #param string $nazwa
* #return Kategoria
*/
public function setNazwa($nazwa)
{
$this->nazwa = $nazwa;
return $this;
}
/**
* Get nazwa
*
* #return string
*/
public function getNazwa()
{
return $this->nazwa;
}
/**
* Get idkategoria
*
* #return integer
*/
public function getIdkategoria()
{
return $this->idkategoria;
}
}
This is a fragment I modified in Ksiazka class. I added , inversedBy="ksiazki"
/**
* #var \AppBundle\Entity\Kategoria
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Kategoria", inversedBy="ksiazki")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idKategoria", referencedColumnName="idKategoria")
* })
*/
private $idkategoria;
This is entire Ksiazka class with ManyToOne relation.
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Ksiazka
*
* #ORM\Table(name="ksiazka", indexes={#ORM\Index(name="idKategoria_idx", columns={"idKategoria"})})
* #ORM\Entity
*/
class Ksiazka
{
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=45, nullable=true)
*/
private $autor;
/**
* #var string
*
* #ORM\Column(name="opis", type="text", length=65535, nullable=true)
*/
private $opis;
/**
* #var string
*
* #ORM\Column(name="cena", type="decimal", precision=10, scale=2, nullable=true)
*/
private $cena;
/**
* #var string
*
* #ORM\Column(name="obrazek", type="string", length=45, nullable=true)
*/
private $obrazek;
/**
* #var string
*
* #ORM\Column(name="wydawnictwo", type="string", length=45, nullable=true)
*/
private $wydawnictwo;
/**
* #var string
*
* #ORM\Column(name="rokWydania", type="string", length=45, nullable=true)
*/
private $rokwydania;
/**
* #var string
*
* #ORM\Column(name="isbn", type="string", length=45)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $isbn;
// Było. Automatycznie wygenerowane bez inversedBy.
// /**
// * #var \AppBundle\Entity\Kategoria
// *
// * #ORM\ManyToOne(targetEntity="AppBundle\Entity\Kategoria")
// * #ORM\JoinColumns({
// * #ORM\JoinColumn(name="idKategoria", referencedColumnName="idKategoria")
// * })
// */
// private $idkategoria;
/**
* #var \AppBundle\Entity\Kategoria
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Kategoria", inversedBy="ksiazki")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idKategoria", referencedColumnName="idKategoria")
* })
*/
private $idkategoria;
/**
* #ORM\OneToMany(targetEntity="Zamowienie_Produkt", mappedBy="ksiazka")
*/
protected $zamowienie_produkty;
/**
* Set autor
*
* #param string $autor
* #return Ksiazka
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Set opis
*
* #param string $opis
* #return Ksiazka
*/
public function setOpis($opis)
{
$this->opis = $opis;
return $this;
}
/**
* Get opis
*
* #return string
*/
public function getOpis()
{
return $this->opis;
}
/**
* Set cena
*
* #param string $cena
* #return Ksiazka
*/
public function setCena($cena)
{
$this->cena = $cena;
return $this;
}
/**
* Get cena
*
* #return string
*/
public function getCena()
{
return $this->cena;
}
/**
* Set obrazek
*
* #param string $obrazek
* #return Ksiazka
*/
public function setObrazek($obrazek)
{
$this->obrazek = $obrazek;
return $this;
}
/**
* Get obrazek
*
* #return string
*/
public function getObrazek()
{
return $this->obrazek;
}
/**
* Set wydawnictwo
*
* #param string $wydawnictwo
* #return Ksiazka
*/
public function setWydawnictwo($wydawnictwo)
{
$this->wydawnictwo = $wydawnictwo;
return $this;
}
/**
* Get wydawnictwo
*
* #return string
*/
public function getWydawnictwo()
{
return $this->wydawnictwo;
}
/**
* Set rokwydania
*
* #param string $rokwydania
* #return Ksiazka
*/
public function setRokwydania($rokwydania)
{
$this->rokwydania = $rokwydania;
return $this;
}
/**
* Get rokwydania
*
* #return string
*/
public function getRokwydania()
{
return $this->rokwydania;
}
/**
* Get isbn
*
* #return string
*/
public function getIsbn()
{
return $this->isbn;
}
/**
* Set idkategoria
*
* #param \AppBundle\Entity\Kategoria $idkategoria
* #return Ksiazka
*/
public function setIdkategoria(\AppBundle\Entity\Kategoria $idkategoria = null)
{
$this->idkategoria = $idkategoria;
return $this;
}
/**
* Get idkategoria
*
* #return \AppBundle\Entity\Kategoria
*/
public function getIdkategoria()
{
return $this->idkategoria;
}
}
Try to delete all methods in Entity class. Then run doctrine:generate:entities command. If not help, try to find mapping errors in profiler. Hope it help.
I have a database with a table users with fields: user_id, username, password, ... . I also have a table players with player_name, player_position, ... AND a FK user_id.
Image relationship:
I genered the entities from the database but now I would like to get the player from user like this $user->getPlayer(). And doctrine didn't generate player in Users entity, only user in Players Entity.
This is what I have now:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #JoinColumn(name="user_id", referencedColumnName="userId")
*/
private $player;
/**
* Get player
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Players
*/
public function getPlayer() {
return $this->player;
}
/**
* Set player
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Players $player
* #return Users
*/
public function setPlayer(\VolleyScout\VolleyScoutBundle\Entity\Players $player = null){
$this->player = $player;
return $this;
}
But when I try $user->getPlayer() I always get null. (And the user_id is in players table)
UPDATE:
My Players Entity:
<?php
namespace VolleyScout\VolleyScoutBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Players
*
* #ORM\Table(name="players", indexes={#ORM\Index(name="fk_players_users1_idx", columns={"user_id"}), #ORM\Index(name="fk_players_teams1_idx", columns={"team_id"}), #ORM\Index(name="fk_players_myteam1_idx", columns={"myteam_id"})})
* #ORM\Entity
*/
class Players
{
/**
* #var string
*
* #ORM\Column(name="player_name", type="string", length=255, nullable=false)
*/
private $playerName;
/**
* #var string
*
* #ORM\Column(name="player_licensenumber", type="string", length=45, nullable=false)
*/
private $playerLicensenumber;
/**
* #var string
*
* #ORM\Column(name="player_position", type="string", nullable=false)
*/
private $playerPosition;
/**
* #var integer
*
* #ORM\Column(name="player_birthyear", type="integer", nullable=true)
*/
private $playerBirthyear;
/**
* #var integer
*
* #ORM\Column(name="player_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $playerId;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Myteam
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Myteam")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="myteam_id", referencedColumnName="myteam_id")
* })
*/
private $myteam;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Teams
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Teams")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="team_id", referencedColumnName="team_id")
* })
*/
private $team;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user;
/**
* Set playerName
*
* #param string $playerName
* #return Players
*/
public function setPlayerName($playerName)
{
$this->playerName = $playerName;
return $this;
}
/**
* Get playerName
*
* #return string
*/
public function getPlayerName()
{
return $this->playerName;
}
/**
* Set playerLicensenumber
*
* #param string $playerLicensenumber
* #return Players
*/
public function setPlayerLicensenumber($playerLicensenumber)
{
$this->playerLicensenumber = $playerLicensenumber;
return $this;
}
/**
* Get playerLicensenumber
*
* #return string
*/
public function getPlayerLicensenumber()
{
return $this->playerLicensenumber;
}
/**
* Set playerPosition
*
* #param string $playerPosition
* #return Players
*/
public function setPlayerPosition($playerPosition)
{
$this->playerPosition = $playerPosition;
return $this;
}
/**
* Get playerPosition
*
* #return string
*/
public function getPlayerPosition()
{
return $this->playerPosition;
}
/**
* Set playerBirthyear
*
* #param integer $playerBirthyear
* #return Players
*/
public function setPlayerBirthyear($playerBirthyear)
{
$this->playerBirthyear = $playerBirthyear;
return $this;
}
/**
* Get playerBirthyear
*
* #return integer
*/
public function getPlayerBirthyear()
{
return $this->playerBirthyear;
}
/**
* Get playerId
*
* #return integer
*/
public function getPlayerId()
{
return $this->playerId;
}
/**
* Set myteam
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Myteam $myteam
* #return Players
*/
public function setMyteam(\VolleyScout\VolleyScoutBundle\Entity\Myteam $myteam = null)
{
$this->myteam = $myteam;
return $this;
}
/**
* Get myteam
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Myteam
*/
public function getMyteam()
{
return $this->myteam;
}
/**
* Set team
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Teams $team
* #return Players
*/
public function setTeam(\VolleyScout\VolleyScoutBundle\Entity\Teams $team = null)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Teams
*/
public function getTeam()
{
return $this->team;
}
/**
* Set user
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Users $user
* #return Players
*/
public function setUser(\VolleyScout\VolleyScoutBundle\Entity\Users $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Users
*/
public function getUser()
{
return $this->user;
}
}
UPDATE 2: In my Users Entity Class I have now:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToMany(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $player;
But it still doesn't work ..
Your annotations are not set correctly (specifically, the JoinColumn). It is interesting that you aren't getting an error, but anyways... replace this:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #JoinColumn(name="user_id", referencedColumnName="userId")
*/
private $player;
with this:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
*/
private $player;
notice that your referencedColumnName should be the name as it is shown in the database, not the Doxtrine entity. Start by fixing those errors, and it should solve the problem.
UPDATE
This is a very different setup it you want a manyToOne relationship.
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToMany(targetEntity="Players", mappedBy="user_id")
*/
private $players;
public function __construct()
{
$this->players = new ArrayCollection();
}
Because $players can now have many values, it should be set as an ArrayCollection. I also made the variable $players instead of $player, for ease of readability.
You should really familiarize yourself with the Symfony Docs, this is a very simple problem that is described very clear in the Symfony docs