Doctrine2 findOneBy returning wrong result - mysql

I am working on a legacy project using Symfony2.3 and the following versions of doctrine components (composer show -i | grep doctrine):
doctrine/annotations v1.1.2
doctrine/cache v1.2.0
doctrine/collections dev-master bcb5377
doctrine/common 2.4.x-dev c94d6ff
doctrine/data-fixtures dev-master 8ffac1c
doctrine/dbal 2.3.x-dev 59c310b
doctrine/doctrine-bundle dev-master a41322d
doctrine/doctrine-fixtures-bundle dev-master 3caec48
doctrine/doctrine-migrations-bundle dev-master 1a7f58d
doctrine/inflector dev-master 8b4b3cc
doctrine/lexer dev-master bc0e1f0
doctrine/migrations dev-master e960224
doctrine/orm 2.3.x-dev 66d8b43
I had to implement a simple db cache system.
I have a storage table and a service class to access it.
The table schema is as follows:
CREATE TABLE `mlp_api_storage` (
`id` TINYINT(4) NOT NULL AUTO_INCREMENT,
`key` VARCHAR(250) NOT NULL,
`value` TEXT NOT NULL,
`is_serialized` TINYINT(4) NOT NULL,
`created` DATETIME NOT NULL,
`ttl` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `Index 2` (`key`)
)
The big issue I am having with this is one some occasions when I try to retrieve a value I get the wrong result.
I am tailing the log file and I can see the query being executed with the correct key value and if I run that directly in MySQL I will get the value I expect but not with doctrine.
Here is the relevant code of the storage service:
/**
* #param string $key
* #param string $value
* #param mixed $ttl
* #return self
*/
public function set($key, $value, $ttl = null)
{
$em = $this->getEntityManager();
$store = $this->fetchEntity($key);
$update = true;
if (!$store) {
$update = false;
$store = new Storage();
}
$store->setKey($key);
if (is_object($value) || is_array($value)) {
$value = serialize($value);
$store->setIsSerialized(true);
} else {
$store->setIsSerialized(false);
}
$store->setValue($value);
$store->setTtl($this->calculateTTL($ttl));
$store->setCreated(new \DateTime());
if ($update) {
$em->merge($store);
} else {
$em->persist($store);
}
$em->flush($store);
return $this;
}
/**
* #param string $key
* #param mixed $default
* #return string|null
*/
public function fetch($key, $default = null)
{
$res = $this->fetchEntity($key);
if ($res) {
if ($this->isValidStorage($res)) {
$value = $res->getValue();
if ($res->getIsSerialized()) {
$value = unserialize($value);
}
return $value;
}
$this->remove($res);
}
if ($default) {
$res = (is_callable($default)) ? $default($this) : $default;
} else {
$res = null;
}
return $res;
}
/**
* #param string $key
* #return Storage
*/
private function fetchEntity($key)
{
/* #var $res Storage */
$res = $this->getEntityManager()
->getRepository(Storage::class)
->findOneBy(['key' => $key]);
if ($res) {
return $res;
}
return null;
}
So using the debugger (and mysql log) I can see that everything is fine up until the line with : ->findOneBy(['key' => $key]);
This will be set with an entity with a different key and value.
I have setup a small example:
$storage->set('test', '1111111111111111111');
$storage->set('test2', '22222222222222222222');
var_dump($storage->fetch('test'));
var_dump($storage->fetch('test2'));
This is returning:
string '1111111111111111111' (length=19)
string '1111111111111111111' (length=19)
Here is what is in the table:
Here is the mysql log output:
66 Query SELECT t0.`key` AS key1, t0.value AS value2, t0.is_serialized AS is_serialized3, t0.created AS created4, t0.ttl AS ttl5, t0.id AS id6 FROM storage t0 WHERE t0.`key` = 'test' LIMIT 1
66 Query SELECT t0.`key` AS key1, t0.value AS value2, t0.is_serialized AS is_serialized3, t0.created AS created4, t0.ttl AS ttl5, t0.id AS id6 FROM storage t0 WHERE t0.`key` = 'test2' LIMIT 1
Am I doing something wrong with doctrine2? I am updating the entity instead of deleting because doctrine will try to insert before deleting.
Thanks!
UPDATE:
Here is the entity code
namespace PitchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Storage
*
* #ORM\Table(name="storage")
* #ORM\Entity
*/
class Storage
{
/**
* #var string
*
* #ORM\Column(name="`key`", type="string", length=250, nullable=false)
*/
private $key;
/**
* #var string
*
* #ORM\Column(name="value", type="text", nullable=false)
*/
private $value;
/**
* #var boolean
*
* #ORM\Column(name="is_serialized", type="boolean", nullable=false)
*/
private $isSerialized;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime", nullable=false)
*/
private $created;
/**
* #var integer
*
* #ORM\Column(name="ttl", type="integer", nullable=true)
*/
private $ttl;
/**
* #var boolean
*
* #ORM\Column(name="id", type="boolean")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* Set key
*
* #param string $key
* #return Storage
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get key
*
* #return string
*/
public function getKey()
{
return $this->key;
}
/**
* Set value
*
* #param string $value
* #return Storage
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set isSerialized
*
* #param boolean $isSerialized
* #return Storage
*/
public function setIsSerialized($isSerialized)
{
$this->isSerialized = $isSerialized;
return $this;
}
/**
* Get isSerialized
*
* #return boolean
*/
public function getIsSerialized()
{
return $this->isSerialized;
}
/**
* Set created
*
* #param \DateTime $created
* #return Storage
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set ttl
*
* #param integer $ttl
* #return Storage
*/
public function setTtl($ttl)
{
$this->ttl = $ttl;
return $this;
}
/**
* Get ttl
*
* #return integer
*/
public function getTtl()
{
return $this->ttl;
}
/**
* Get id
*
* #return boolean
*/
public function getId()
{
return $this->id;
}
}

You have an error in your entity id annotation. Currently it is:
* #ORM\Column(name="id", type="boolean")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
but it should be
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")

Related

How do I fetch association data from a list of users through a many to many relationship in doctrine query builder

I can't figure out how to do this using the query builder in Doctrine:
On a high level, I wan to fetch all of the userTags which are associated to each user, and I am fetching each user from user relationship table by their parent id.
Something like this:
from UserRelationship -> get users by parent_id -> also get each user's associated userTags. It's the last bit that I can't get the userTags. Idealy I would select only the id and name params from that table, as the rest, like company and users is redundant.
I have this query builder query in Symfony 3.* Doctrine 2.*
UserRelationshipRepository.php
protected function getBaseSubordinateQuery($managerId ){
$qb = $this->createQueryBuilder('r');
$qb
->select(
'u.id',
'u.username',
'u.email',
'u.first_name',
'u.last_name',
'u.lastLogin',
'u.userTags', // <-- How do I get these values?
'c.phone',
'c.position as jobTitle',
'co.name as company',
'c.createdAt',
'max(cl.expiresAt) as expiresAt',
'cl.expiresAt',
'c.yearsInPosition as titleSince',
'c.skype',
'c.linkedin',
'c.yearsAtCompany',
'up.path as imgPath',
'up.name as imgName',
'up.format as imgFormat'
)
->innerJoin( 'r.child', 'u' )
->innerJoin( 'u.clientInfo', 'c' )
->leftJoin( 'u.userTags', 'ut' )
->where('ut IS NOT NULL')
->leftJoin( 'u.company', 'co' )
->leftJoin( 'c.clientLicense', 'cl' )
->leftJoin( 'u.userPhotos', 'up' )
->where ( $qb->expr()->eq('r.parent', ':manager') )
->setParameter('manager', $managerId)
;
return $qb;
Note: as it is, that query gives me an error: 500 Internal Server Error. [Semantical Error] line 0, col 76 near 'userTags, c.phone,': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
User.php
/**
* #var \Doctrine\Common\Collections\Collection|\Reddin\Bundle\CMSBundle\Entity\UserTag[]
*
* #ORM\ManyToMany(targetEntity="Reddin\Bundle\CMSBundle\Entity\UserTag", inversedBy="users")
* #ORM\JoinTable(name="users_user_tags")
*
* #JMS\Groups({"tags"})
* #JMS\MaxDepth(2)
*/
protected $userTags;
UserTag.php
class UserTag
{
use Timestampable;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Many UserTags belong to one Company.
*
* #ORM\ManyToOne(targetEntity="Reddin\Bundle\CMSBundle\Entity\Company", inversedBy="userTags", fetch="EXTRA_LAZY")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
* #JMS\MaxDepth(2)
*/
private $company;
/**
* #var \Doctrine\Common\Collections\Collection|\Reddin\Bundle\UserAccountBundle\Entity\User[]
*
* #ORM\ManyToMany(targetEntity="Reddin\Bundle\UserAccountBundle\Entity\User", mappedBy="userTags", fetch="EXTRA_LAZY")
* #JMS\MaxDepth(2)
*/
private $users;
/**
* Company constructor.
*/
public function __construct()
{
$this->users = new ArrayCollection();
}
public function __toString()
{
return "" . $this->getName();
}
/**
* Get id
*
* #return int
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return UserTag
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* #return ArrayCollection|User[]
*/
public function getUsers()
{
return $this->users;
}
/**
* #return UserTag
*/
public function getCompany() {
return $this->company;
}
/**
* #param Company $company
* #return UserTag
*/
public function setCompany(Company $company = null) {
$this->company = $company;
return $this;
}
}
Replace
'u.userTags',
with
'ut'
This will solve the error you are getting, but probably you will get others.
I suggest change the query to:
$qb
->select(
'r',
'u',
'ut',
...
Also replace the 2nd where to:
->andWhere ( $qb->expr()->eq('r.parent', ':manager') )
Then you can fetch the tags for each user:
$userRel->getChild()->getUserTags();

Unable to retrieve all fields from user table with app.user using TWIG and Symfony 2, FOSUserBundle

I am currently making a website and I have an entity User, which has several fields. But when I am trying retrieve the current user that is logged in it only retrieves the username.
Fields in UserType are as follows:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email')
->add('name')
->add('building')
->add('room')
;
}
I am using this html code and TWIG to retrieve the fields:
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Building</th>
<th>Room Number</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ app.user.name }}</td>
<td>{{ app.user.building }}</td>
<td>{{ app.user.room }}</td>
<td>{{ app.user.email }}</td>
</tr>
</tbody>
</table>
But when I view table in the browser I only get the email field populated in the table?
User Entity:
<?php
namespace FYProject\ProjectBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Entity
* #ORM\Table(name="fyp_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*/
protected $username;
/**
* #var string
*/
protected $password;
/**
* #var string
*/
protected $name;
/**
* #var string
*/
protected $lastname;
/**
* #var string
*/
protected $school;
/**
* #var string
*/
protected $qualification;
/**
* #var string
*/
protected $modeofstudy;
/**
* #var string
*/
protected $programmecode;
/**
* #var integer
*/
protected $programmeyear;
/**
* #var datetime
*/
protected $startdate;
/**
* #var string
*/
protected $building;
/**
* #var integer
*/
protected $room;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return Entity
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return Entity
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set name
*
* #param string $name
* #return Entity
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set school
*
* #param string $school
* #return Entity
*/
public function setSchool($school)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* #return string
*/
public function getSchool()
{
return $this->school;
}
/**
* set qualification
*
* #param string qualification
* #return Entity
*/
public function setQualification($qualification){
$this->qualification = $qualification;
return $this;
}
/**
* get qualification
*
* #return string
*/
public function getQualification(){
return $this->qualification;
}
/**
* set modeofstudy
*
* #param string modeofstudy
* #return Entity
*/
public function setModeofstudy($modeofstudy){
$this->modeofstudy = $modeofstudy;
return $this;
}
/**
* get modeofstudy
*
* #return string
*/
public function getModeofstudy(){
return $this->modeofstudy;
}
/**
* set programmecode
*
* #param string programmecode
* #return Entity
*/
public function setProgrammecode($programmecode){
$this->programmecode = $programmecode;
return $this;
}
/**
* get programmecode
*
* #return string
*/
public function getProgrammecode(){
return $this->programmecode;
}
/**
* set programmeyear
*
* #param integer programmeyearn
* #return Entity
*/
public function setProgrammeyear($programmeyear){
$this->programmecode = $programmeyear;
return $this;
}
/**
* get programmecode
*
* #return integer
*/
public function getProgrammeyear(){
return $this->programmeyear;
}
/**
* set startdate
*
* #param datetime startdate
* #return Entity
*/
public function setStartdate($startdate){
$this->startdate = $startdate;
return $this;
}
/**
* get startdate
*
* #return datetime
*/
public function getStartdate(){
return $this->startdate;
}
/**
* set lastname
*
* #param string lastname
* #return Entity
*/
public function setLastname($lastname){
$this->lastname = $lastname;
return $this;
}
/**
* get lastname
*
* #return string
*/
public function getLastname(){
return $this->lastname;
}
/**
* set building
* #param string building
* #return Entity
*/
public function setBuilding($building){
$this->building = $building;
return $this;
}
/**
* get building
*
* #return string
*/
public function getBuilding(){
return $this->building;
}
/**
* set room
* #param integer room
* #return Entity
*/
public function setRoom($room){
$this->room = $room;
return $this;
}
/**
* get room
*
* #return integer
*/
public function getRoom(){
return $this->room;
}
public function __construct(){
parent::__construct();
}
}
When registering the current fields are returning null, using dump(app.user):
User {#306 ▼
#id: 9
#name: null
#lastname: null
#school: null
#qualification: null
#modeofstudy: null
#programmecode: null
#programmeyear: null
#startdate: null
#building: null
#room: null
Use this docummentation to override a Form Type
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
Update your database schema
Clear your cache
Problem solved
I wasnt setting the #ORM\column for each field in the Entity User. Updated User Entity:
<?php
namespace FYProject\ProjectBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Entity
* #ORM\Table(name="fyp_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100)
*
*/
protected $name;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=100)
*/
protected $lastname;
/**
* #var string
*
* #ORM\Column(name="school", type="string", length=100)
*/
protected $school;
/**
* #var string
*
* #ORM\Column(name="qualification", type="string", length=50)
*/
protected $qualification;
/**
* #var string
*
* #ORM\Column(name="modeofstudy", type="string", length=50)
*/
protected $modeofstudy;
/**
* #var string
*
* #ORM\Column(name="programmecode", type="string", length=50)
*/
protected $programmecode;
/**
* #var integer
*
* #ORM\Column(name="programmeyear", type="integer", length=10)
*/
protected $programmeyear;
/**
* #var datetime
*
* #ORM\Column(name="startdate", type="datetime", length=50)
*/
protected $startdate;
/**
* #var string
*
* #ORM\Column(name="building", type="string", length=50)
*/
protected $building;
/**
* #var integer
*
* #ORM\Column(name="room", type="integer", length=50)
*/
protected $room;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Entity
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set school
*
* #param string $school
* #return Entity
*/
public function setSchool($school)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* #return string
*/
public function getSchool()
{
return $this->school;
}
/**
* set qualification
*
* #param string $qualification
* #return Entity
*/
public function setQualification($qualification){
$this->qualification = $qualification;
return $this;
}
/**
* get qualification
*
* #return string
*/
public function getQualification(){
return $this->qualification;
}
/**
* set modeofstudy
*
* #param string $modeofstudy
* #return Entity
*/
public function setModeofstudy($modeofstudy){
$this->modeofstudy = $modeofstudy;
return $this;
}
/**
* get modeofstudy
*
* #return string
*/
public function getModeofstudy(){
return $this->modeofstudy;
}
/**
* set programmecode
*
* #param string $programmecode
* #return Entity
*/
public function setProgrammecode($programmecode){
$this->programmecode = $programmecode;
return $this;
}
/**
* get programmecode
*
* #return string
*/
public function getProgrammecode(){
return $this->programmecode;
}
/**
* set programmeyear
*
* #param integer $programmeyear
* #return Entity
*/
public function setProgrammeyear($programmeyear){
$this->programmecode = $programmeyear;
return $this;
}
/**
* get programmecode
*
* #return integer
*/
public function getProgrammeyear(){
return $this->programmeyear;
}
/**
* set startdate
*
* #param datetime $startdate
* #return Entity
*/
public function setStartdate($startdate){
$this->startdate = $startdate;
return $this;
}
/**
* get startdate
*
* #return datetime
*/
public function getStartdate(){
return $this->startdate;
}
/**
* set lastname
*
* #param string $lastname
* #return Entity
*/
public function setLastname($lastname){
$this->lastname = $lastname;
return $this;
}
/**
* get lastname
*
* #return string
*/
public function getLastname(){
return $this->lastname;
}
/**
* set building
* #param string $building
* #return Entity
*/
public function setBuilding($building){
$this->building = $building;
return $this;
}
/**
* get building
*
* #return string
*/
public function getBuilding(){
return $this->building;
}
/**
* set room
* #param integer $room
* #return Entity
*/
public function setRoom($room){
$this->room = $room;
return $this;
}
/**
* get room
*
* #return integer
*/
public function getRoom(){
return $this->room;
}
public function __construct(){
parent::__construct();
}
}
Problem Solved! Thanks for the help!

Doctrine2 Primary Key

This is my Doctrine2 Annotation file, which is returning me this error
MappingException: No identifier/primary key specified for Entity
"WbsGo\clientsBundle\Entity\VtigerPortalinfo". Every Entity must have
an identifier/primary key.
In DB, the field ID is set to Primary Key... So I don't know where is the problem....
<?php
namespace WbsGo\clientsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* VtigerPortalinfo
*/
class VtigerPortalinfo
{
/**
* #var string
*/
private $userName;
/**
* #var string
*/
private $userPassword;
/**
* #var string
*/
private $type;
/**
* #var \DateTime
*/
private $lastLoginTime;
/**
* #var \DateTime
*/
private $loginTime;
/**
* #var \DateTime
*/
private $logoutTime;
/**
* #var integer
*/
private $isactive;
/**
* #var \WbsGo\clientsBundle\Entity\VtigerContactdetails
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Set userName
*
* #param string $userName
* #return VtigerPortalinfo
*/
public function setUserName($userName)
{
$this->userName = $userName;
return $this;
}
/**
* Get userName
*
* #return string
*/
public function getUserName()
{
return $this->userName;
}
/**
* Set userPassword
*
* #param string $userPassword
* #return VtigerPortalinfo
*/
public function setUserPassword($userPassword)
{
$this->userPassword = $userPassword;
return $this;
}
/**
* Get userPassword
*
* #return string
*/
public function getUserPassword()
{
return $this->userPassword;
}
/**
* Set type
*
* #param string $type
* #return VtigerPortalinfo
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set lastLoginTime
*
* #param \DateTime $lastLoginTime
* #return VtigerPortalinfo
*/
public function setLastLoginTime($lastLoginTime)
{
$this->lastLoginTime = $lastLoginTime;
return $this;
}
/**
* Get lastLoginTime
*
* #return \DateTime
*/
public function getLastLoginTime()
{
return $this->lastLoginTime;
}
/**
* Set loginTime
*
* #param \DateTime $loginTime
* #return VtigerPortalinfo
*/
public function setLoginTime($loginTime)
{
$this->loginTime = $loginTime;
return $this;
}
/**
* Get loginTime
*
* #return \DateTime
*/
public function getLoginTime()
{
return $this->loginTime;
}
/**
* Set logoutTime
*
* #param \DateTime $logoutTime
* #return VtigerPortalinfo
*/
public function setLogoutTime($logoutTime)
{
$this->logoutTime = $logoutTime;
return $this;
}
/**
* Get logoutTime
*
* #return \DateTime
*/
public function getLogoutTime()
{
return $this->logoutTime;
}
/**
* Set isactive
*
* #param integer $isactive
* #return VtigerPortalinfo
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return integer
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Set id
*
* #param \WbsGo\clientsBundle\Entity\VtigerContactdetails $id
* #return VtigerPortalinfo
*/
public function setId(\WbsGo\clientsBundle\Entity\VtigerContactdetails $id = null)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return \WbsGo\clientsBundle\Entity\VtigerContactdetails
*/
public function getId()
{
return $this->id;
}
}
Maybe if you change the annotation line of $id for this line:
*ORM\GeneratedValue(strategy="IDENTITY")

From raw MySQL query to symfony 2

Im trying to fetch a symfony2 entity using this query:
SELECT g . *,
(SELECT Count(gc.`code`) AS `codecount`
FROM giftcode gc
WHERE gc.`gift_id` = g.`id`
AND gc.`provided` IS NULL
GROUP BY gc.`gift_id`) AS gcodecount
FROM gift g
WHERE Now() >= g.validbegin
AND Now() <= g.validend
So far I have this:
$query = $giftRepository->createQueryBuilder('p')
->where(':now >= p.validbegin AND :now <= p.validend')
->setParameter('now', new \DateTime())
->orderBy('p.points', $hts)
->getQuery();
$gifts = $query->getResult();
Its working but incomplete, I have no idea how can I call the second table (giftcode) inside the query just like I did it on the raw query.
EDIT:
namespace Done\PunctisBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Gift
*
* #ORM\Table(name="gift")
* #ORM\Entity
*/
class Gift
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="redemption", type="string", nullable=true)
*/
private $redemption;
/**
* #var \Date $validbegin
*
* #ORM\Column(name="validbegin", type="date", nullable=true)
*/
private $validbegin;
/**
* #var \Date $validend
*
* #ORM\Column(name="validend", type="date", nullable=true)
*/
private $validend;
/**
* #var integer
*
* #ORM\Column(name="amount", type="integer", nullable=true)
*/
private $amount;
/**
* #var integer
*
* #ORM\Column(name="points", type="integer")
*/
private $points;
/**
* #var boolean
*
* #ORM\Column(name="verified", type="boolean")
*/
private $verified;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255)
*/
private $image;
/**
* #var string
*
* #ORM\Column(name="price", type="integer")
*/
private $price;
/**
* #var string
*
* #ORM\Column(name="discount", type="integer")
*/
private $discount;
/**
* #var \Done\PunctisBundle\Entity\Brand
*
* #ORM\ManyToOne(targetEntity="Done\PunctisBundle\Entity\Brand", inversedBy="gifts")
*/
protected $brand;
/**
* #var \Done\PunctisBundle\Entity\GiftCode
*
* #ORM\OneToMany(targetEntity="Done\PunctisBundle\Entity\GiftCode", mappedBy="gift", cascade={"persist"})
*/
protected $codes;
/**
* Constructor
*/
public function __construct()
{
$this->codes = new \Doctrine\Common\Collections\ArrayCollection();
$this->verified = false;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Gift
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Gift
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set redemption
*
* #param string $redemption
* #return Gift
*/
public function setRedemption($redemption)
{
$this->redemption = $redemption;
return $this;
}
/**
* Get redemption
*
* #return string
*/
public function getRedemption()
{
return $this->redemption;
}
/**
* Set points
*
* #param integer $points
* #return Gift
*/
public function setPoints($points)
{
$this->points = $points;
return $this;
}
/**
* Get points
*
* #return integer
*/
public function getPoints()
{
return $this->points;
}
/**
* Set amount
*
* #param integer $amount
* #return Gift
*/
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
/**
* Get amount
*
* #return integer
*/
public function getAmount()
{
return $this->amount;
}
/**
* Set verified
*
* #param boolean $verified
* #return Gift
*/
public function setVerified($verified)
{
$this->verified = $verified;
return $this;
}
/**
* Get verified
*
* #return boolean
*/
public function getVerified()
{
return $this->verified;
}
/**
* Set image
*
* #param string $image
* #return Gift
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set price
*
* #param integer $price
* #return Gift
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return integer
*/
public function getPrice()
{
return $this->price;
}
/**
* Set discount
*
* #param integer $discount
* #return Gift
*/
public function setDiscount($discount)
{
$this->discount = $discount;
return $this;
}
/**
* Get discount
*
* #return integer
*/
public function getDiscount()
{
return $this->discount;
}
/**
* Set brand
*
* #param \Done\PunctisBundle\Entity\Brand $brand
* #return Gift
*/
public function setBrand(\Done\PunctisBundle\Entity\Brand $brand = null)
{
$this->brand = $brand;
return $this;
}
/**
* Get brand
*
* #return \Done\PunctisBundle\Entity\Brand
*/
public function getBrand()
{
return $this->brand;
}
/**
* Add codes
*
* #param \Done\PunctisBundle\Entity\GiftCode $codes
* #return Gift
*/
public function addCode(\Done\PunctisBundle\Entity\GiftCode $codes)
{
$this->codes[] = $codes;
return $this;
}
/**
* Set validbegin
*
* #param \Date $validbegin
* #return UserInfo
*/
public function setValidbegin($validbegin)
{
$this->validbegin = $validbegin;
return $this;
}
/**
* Get validbegin
*
* #return \Date
*/
public function getValidbegin()
{
return $this->validbegin;
}
/**
* Set validend
*
* #param \Date $validend
* #return UserInfo
*/
public function setValidend($validend)
{
$this->validend = $validend;
return $this;
}
/**
* Get validend
*
* #return \Date
*/
public function getValidend()
{
return $this->validend;
}
/**
* Remove codes
*
* #param \Done\PunctisBundle\Entity\GiftCode $codes
*/
public function removeCode(\Done\PunctisBundle\Entity\GiftCode $codes)
{
$this->codes->removeElement($codes);
}
/**
* Get codes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCodes()
{
return $this->codes;
}
}
<?php
namespace Done\PunctisBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* GiftCode
*
* #ORM\Table(name="giftcode")
* #ORM\Entity
*/
class GiftCode
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=255)
*/
private $code;
/**
* #var \DateTime
*
* #ORM\Column(name="provided", type="datetime", nullable=true)
*/
private $provided;
/**
* #var \Done\PunctisBundle\Entity\Gift
*
* #ORM\ManyToOne(targetEntity="Done\PunctisBundle\Entity\Gift", inversedBy="codes")
*/
protected $gift;
public function __construct( )
{
$this->provided = null;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* #param string $code
* #return GiftCode
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set provided
*
* #param \DateTime $provided
* #return GiftCode
*/
public function setProvided($provided)
{
$this->provided = $provided;
return $this;
}
/**
* Get provided
*
* #return \DateTime
*/
public function getProvided()
{
return $this->provided;
}
/**
* Set user
*
* #param string $user
* #return GiftCode
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return string
*/
public function getUser()
{
return $this->user;
}
/**
* Set gift
*
* #param \Done\PunctisBundle\Entity\Gift $gift
* #return GiftCode
*/
public function setGift(\Done\PunctisBundle\Entity\Gift $gift = null)
{
$this->gift = $gift;
return $this;
}
/**
* Get gift
*
* #return \Done\PunctisBundle\Entity\Gift
*/
public function getGift()
{
return $this->gift;
}
}
You could try something like:
$query=$entityManager->createQuery("SELECT g
FROM gift g
WHERE Now() >= g.validbegin
AND Now() <= g.validend
AND gc.provided IS NULL");
$list=$query->getResults();
Now you can iterate through $list and every element will be a Gift.
To know how many Giftcodes does a Gift have, you only need to do:
$qtty= count( $gift->getCodes());

How to access object method in twig from doctrine inner join

I have a member entity and a friend entity.
I get all the friends of a member by joining the tables.
I join the members on the friends via member_id.
TABLE STRUCTURE:
Members
member_id, full_name, email, password, date_joined
Friends
friendship_id, member_id, friend_id
Everything is fine but I can't get the full_name of the friend_id.
I ran the command line to generate the getters, setters, and join info in the entities.
In twig I get the friends array from the controller and calling friend.fullName returns my name, not my friends names but I joined on member_id that so thats fine.
I need to get the fullName of the member with the id of friend_id without 2 queries.
Ex.
member_id: 1, full_name:John
Friend
member_id: 22, full_name:Billy
I can call friend.friendId and it will return the 22, I'm stumped on getting the fullName
Member Entity
<?php
namespace Pixbelly\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Pixbelly\AppBundle\Entity\Members
*
* #ORM\Table(name="members")
* #ORM\Entity(repositoryClass="Pixbelly\AppBundle\Repository\MembersRepository")
*/
class Members
{
/**
* #var integer $memberId
*
* #ORM\Column(name="member_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $memberId;
/**
* #var string $fullName
*
* #ORM\Column(name="full_name", type="string", length=255, nullable=false)
*/
private $fullName;
/**
* #var string $email
*
* #ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* #var string $password
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var \DateTime $dateJoined
*
* #ORM\Column(name="date_joined", type="datetime", nullable=false)
*/
private $dateJoined;
/**
* #ORM\OneToMany(targetEntity="Friends", mappedBy="member")
*/
protected $friends;
public function __construct()
{
$this->friends = new ArrayCollection();
}
/**
* Get memberId
*
* #return integer
*/
public function getMemberId()
{
return $this->memberId;
}
/**
* Set fullName
*
* #param string $fullName
* #return Members
*/
public function setFullName($fullName)
{
$this->fullName = $fullName;
return $this;
}
/**
* Get fullName
*
* #return string
*/
public function getFullName()
{
return $this->fullName;
}
/**
* Set email
*
* #param string $email
* #return Members
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
* #return Members
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set dateJoined
*
* #param \DateTime $dateJoined
* #return Members
*/
public function setDateJoined($dateJoined)
{
$this->dateJoined = $dateJoined;
return $this;
}
/**
* Get dateJoined
*
* #return \DateTime
*/
public function getDateJoined()
{
return $this->dateJoined;
}
/**
* Add friends
*
* #param Pixbelly\AppBundle\Entity\Friends $friends
* #return Members
*/
public function addFriend(\Pixbelly\AppBundle\Entity\Friends $friends)
{
$this->friends[] = $friends;
return $this;
}
/**
* Remove friends
*
* #param Pixbelly\AppBundle\Entity\Friends $friends
*/
public function removeFriend(\Pixbelly\AppBundle\Entity\Friends $friends)
{
$this->friends->removeElement($friends);
}
/**
* Get friends
*
* #return Doctrine\Common\Collections\Collection
*/
public function getFriends()
{
return $this->friends;
}
}
Friends Entity
<?php
namespace Pixbelly\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pixbelly\AppBundle\Entity\Friends
*
* #ORM\Table(name="friends")
* #ORM\Entity(repositoryClass="Pixbelly\AppBundle\Repository\FriendsRepository")
*/
class Friends
{
/**
* #var integer $id
*
* #ORM\Column(name="friendship_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $friendshipId;
/**
* #var integer $memberId
*
* #ORM\Column(name="member_id", type="integer", nullable=false)
*/
private $memberId;
/**
* #var integer $friendId
*
* #ORM\Column(name="friend_id", type="integer", nullable=false)
*/
private $friendId;
/**
* #ORM\ManyToOne(targetEntity="Members", inversedBy="friends")
* #ORM\JoinColumn(name="member_id", referencedColumnName="member_id")
*/
protected $member;
/**
* Get friendshipId
*
* #return integer
*/
public function getFriendshipId()
{
return $this->friendshipId;
}
/**
* Set memberId
*
* #param integer $memberId
* #return Friends
*/
public function setMemberId($memberId)
{
$this->memberId = $memberId;
return $this;
}
/**
* Get memberId
*
* #return integer
*/
public function getMemberId()
{
return $this->memberId;
}
/**
* Set friendId
*
* #param integer $friendId
* #return Friends
*/
public function setFriendId($friendId)
{
$this->friendId = $friendId;
return $this;
}
/**
* Get friendId
*
* #return integer
*/
public function getFriendId()
{
return $this->friendId;
}
/**
* Set member
*
* #param Pixbelly\AppBundle\Entity\Members $member
* #return Friends
*/
public function setMember(\Pixbelly\AppBundle\Entity\Members $member = null)
{
$this->member = $member;
return $this;
}
/**
* Get member
*
* #return Pixbelly\AppBundle\Entity\Members
*/
public function getMember()
{
return $this->member;
}
}