in my test project I have 2 entities :
- endUser (extend of FOSUserBundle)
- Rezo (will containt approved relation between two members)
the both entities have been defined as :
EndUser Entity :
<?php
namespace Core\CustomerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* EndUser
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
*/
class EndUser extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* #var string
* #ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaissance", type="datetime", nullable=true)
*/
private $DateNaissance;
/**
* #ORM\OneToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"persist", "merge", "remove"})
* #ORM\JoinColumn(name="adressbook_id", referencedColumnName="id", nullable=true)
*/
private $adressbook;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Discipline", mappedBy="endusers")
*/
private $disciplines;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Experiences", mappedBy="endusers")
*/
private $experiences;
/**
* #var string
* #ORM\Column(name="avatar", type="string", length=255, nullable=true)
*/
private $avatar;
/**
* #var string
* #ORM\Column(name="repository", type="string", length=255, nullable=true)
*/
private $repository;
/**
* #ORM\OneToMany(targetEntity="Core\MyEquiBookBundle\Entity\NiveauEndUser", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $niveaux;
/**
* #ORM\OneToMany(targetEntity="Core\GeneralBundle\Entity\Rezo", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $friends;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->disciplines = new \Doctrine\Common\Collections\ArrayCollection();
$this->niveaux = new \Doctrine\Common\Collections\ArrayCollection();
$this->experiences = new \Doctrine\Common\Collections\ArrayCollection();
$this->friends = new \Doctrine\Common\Collections\ArrayCollection();
$this->expiresAt = new \DateTime("+1 year");
$this->credentialsExpireAt = new \DateTime("+1 year");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set avatar
*
* #param string $avatar
* #return EndUser
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set repository
*
* #param string $repository
* #return EndUser
*/
public function setRepository($repository)
{
$this->repository = $repository;
return $this;
}
/**
* Get repository
*
* #return string
*/
public function getRepository()
{
return $this->repository;
}
/**
* Set adressbook
*
* #param \Core\CustomerBundle\Entity\EndUser $adressbook
* #return EndUser
*/
public function setAdressbook(\Core\CustomerBundle\Entity\EndUser $adressbook = null)
{
$this->adressbook = $adressbook;
return $this;
}
/**
* Get adressbook
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getAdressbook()
{
return $this->adressbook;
}
/**
* Add disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
* #return EndUser
*/
public function addDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines[] = $disciplines;
return $this;
}
/**
* Remove disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
*/
public function removeDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines->removeElement($disciplines);
}
/**
* Get disciplines
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDisciplines()
{
return $this->disciplines;
}
/**
* Add niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
* #return EndUser
*/
public function addNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux[] = $niveaux;
return $this;
}
/**
* Remove niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
*/
public function removeNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux->removeElement($niveaux);
}
/**
* Get niveaux
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNiveaux()
{
return $this->niveaux;
}
/**
* Add experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
* #return EndUser
*/
public function addExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences[] = $experiences;
return $this;
}
/**
* Remove experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
*/
public function removeExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences->removeElement($experiences);
}
/**
* Get experiences
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getExperiences()
{
return $this->experiences;
}
/**
* Add friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
* #return EndUser
*/
public function addFriend(\Core\GeneralBundle\Entity\Rezo $friends )
{
$this->friends[] = $friends;
return $this;
}
/**
* Remove friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
*/
public function removeFriend(\Core\GeneralBundle\Entity\Rezo $friends)
{
$this->friends->removeElement($friends);
}
/**
* Get friends
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFriends()
{
return $this->friends;
}
/**
* Set firstname
*
* #param string $firstname
* #return EndUser
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return EndUser
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set DateNaissance
*
* #param \DateTime $dateNaissance
* #return EndUser
*/
public function setDateNaissance($dateNaissance)
{
$this->DateNaissance = $dateNaissance;
return $this;
}
/**
* Get DateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->DateNaissance;
}
}
Rezo Entity :
<?php
namespace Core\GeneralBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Rezo
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\GeneralBundle\Entity\RezoRepository")
*/
class Rezo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="RequestedDate", type="datetime")
*/
private $requestedDate;
/**
* #var \DateTime
*
* #ORM\Column(name="AcceptedDate", type="datetime", nullable=true)
*/
private $acceptedDate;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\Enduser", inversedBy="friends", cascade={"refresh"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $enduser;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"refresh"})
* #ORM\JoinColumn(name="friendwith", referencedColumnName="id")
*/
protected $friendwith;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set requestedDate
*
* #param \DateTime $requestedDate
* #return Rezo
*/
public function setRequestedDate($requestedDate)
{
$this->requestedDate = $requestedDate;
return $this;
}
/**
* Get requestedDate
*
* #return \DateTime
*/
public function getRequestedDate()
{
return $this->requestedDate;
}
/**
* Set acceptedDate
*
* #param \DateTime $acceptedDate
* #return Rezo
*/
public function setAcceptedDate($acceptedDate)
{
$this->acceptedDate = $acceptedDate;
return $this;
}
/**
* Get acceptedDate
*
* #return \DateTime
*/
public function getAcceptedDate()
{
return $this->acceptedDate;
}
/**
* Set enduser
*
* #param \Core\CustomerBundle\Entity\EndUser $enduser
* #return Rezo
*/
public function setEnduser(\Core\CustomerBundle\Entity\EndUser $enduser = null)
{
$this->enduser = $enduser;
return $this;
}
/**
* Get enduser
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getEnduser()
{
return $this->enduser;
}
/**
* Set friendwith
*
* #param \Core\CustomerBundle\Entity\EndUser $friendwith
* #return Rezo
*/
public function setFriendwith(\Core\CustomerBundle\Entity\EndUser $friendwith = null)
{
$this->friendwith = $friendwith;
return $this;
}
/**
* Get friendwith
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getFriendwith()
{
return $this->friendwith;
}
when I run :
app/console doctrine:schema:update --force
The following MySQL table has been created :
CREATE TABLE IF NOT EXISTS `Rezo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`friendwith` int(11) DEFAULT NULL,
`RequestedDate` datetime NOT NULL,
`AcceptedDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_681FC4BA76ED395` (`user_id`),
KEY `IDX_681FC4B1094AD75` (`friendwith`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
In the RezoController.php controller I would like to give to endUser opportunity to accept a contact request fot this I have created a function named : acceptnewrequestAction($id)
public function acceptnewrequestAction($id){
$em = $this->getDoctrine()->getManager();
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->find($id);
$user1 = $rezo->getEnduser();
$user2 = $rezo->getFriendwith();
$dateRequest = $rezo->getRequestedDate();
$rezo->setAcceptedDate(new \DateTime('now'));
$em->persist($rezo);
$em->flush();
/* check if inverse relation exist */
$query = $em->CreateQuerybuilder();
$query->select('t0.id');
$query->from('CoreGeneralBundle:Rezo','t0');
$query->where('t0.acceptedDate IS NULL');
$query->andWhere('t0.enduser = :userId');
$query->andWhere('t0.friendwith =:userId2');
$query->SetParameters(array('userId'=> $user2, 'userId2'=>$user1));
$result = $query->getQuery()->getOneOrNullResult();
if ( is_object($result))
{
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->findById($result->getId());
$rezo->setAcceptedDate(new \DateTime('now'));
} else {
$rezo = new Rezo();
$rezo->setRequestedDate(new \Datetime('now'));
$rezo->setAcceptedDate(new \DateTime('now'));
$rezo->Setenduser($user2);
$rezo->setFriendwith($user1);
}
$em->persist($rezo);
$em->flush();
return $this->render(controller('CoreGeneralBundle:Rezo:RezoList'));
}
I would like to know how I can use results to know if one object if found or return is Null and in case it exists update it or create a new one.
thank you for your help
getOneOrNullResult method tells you if any record in database is found, or not.
If it return null, it means that you have some results, and in your case you have to insert new one.
But when it exists some records, this method will return object instance of your entity. That means in your case you have to update existing record.
Please remember, that getOneOrNullResult method throws exception, when result set is not unique.
Related
I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;
I can't access to user entity by topic entity.
In the template twig i use dump to display the result query...:
{% for forum in listForums %}
{{ dump (forum.topics.last)}}
....
we can see that User entity is empty (null):
Topic {#1456 ▼
-Forum: Forum {#435 ▶}
-Posts: PersistentCollection {#1457 ▶}
-id: 65
-title: "How to go over there"
-User: User {#1294 ▼
-_entityPersister: BasicEntityPersister {#1291 ▶}
-_identifier: array:1 [▶]
+__isInitialized__: false
-Topics: null
#id: null
-pseudo: null
-name: null
-firstname: null
-website: null
-avatar: null
-signature: null
-location: null
-registration: null
-lastVisit: null
-rank: null
-nbPost: null
-nbTopic: null
#username: null
#usernameCanonical: null
#email: null
#emailCanonical: null
#enabled: null
#salt: null
#password: null
#plainPassword: null
#lastLogin: null
#confirmationToken: null
#passwordRequestedAt: null
#groups: null
#locked: null
#expired: null
#expiresAt: null
#roles: null
#credentialsExpired: null
#credentialsExpireAt: null
}
-viewCount: 23
-dateCreation: DateTime {#1455 ▶}
-replyCount: 123
-slug: "slug_sluggg"
-genre: "genre"
-lastPost: 25
-content: """
<p>test</p>\r\n
\r\n
<p>test2</p>\r\n
\r\n
<p>test3</p>
"""
}
Part of Controller
class FController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$listForums = $em->getRepository('BISSAPForumBundle:Forum')->findAllOrderByCategory();
return $this->render('BISSAPForumBundle:F:index-forum.html.twig', array('listForums' => $listForums, 'user' => $user));
}
}
Topic.php
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/*use BISSAP\BodyConcept\Entity\Forum;
*/
/**
* Topic
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\TopicRepository")
*/
class Topic
{
/**
* #ORM\ManyToOne(targetEntity="Forum", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(name="forum_id", referencedColumnName="id")
*/
private $Forum;
/**
* #var ArrayCollection $Posts
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="Topic", cascade={"persist", "remove", "merge"})
*/
private $Posts;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $User;
/**
* #var integer
*
* #ORM\Column(name="view_count", type="integer")
*/
private $viewCount;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var integer
*
* #ORM\Column(name="reply_count", type="integer")
*/
private $replyCount;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="genre", type="string", length=255)
*/
private $genre;
/**
* #var integer
*
* #ORM\Column(name="last_post", type="integer")
*/
private $lastPost;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Topic
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user
*
* #param integer $user
* #return Topic
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUser()
{
return $this->user;
}
/**
* Set viewCount
*
* #param integer $viewCount
* #return Topic
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* Get viewCount
*
* #return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Topic
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set replyCount
*
* #param integer $replyCount
* #return Topic
*/
public function setReplyCount($replyCount)
{
$this->replyCount = $replyCount;
return $this;
}
/**
* Get replyCount
*
* #return integer
*/
public function getReplyCount()
{
return $this->replyCount;
}
/**
* Set slug
*
* #param string $slug
* #return Topic
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set genre
*
* #param string $genre
* #return Topic
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* #return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* Set lastPost
*
* #param integer $lastPost
* #return Topic
*/
public function setLastPost($lastPost)
{
$this->lastPost = $lastPost;
return $this;
}
/**
* Get lastPost
*
* #return integer
*/
public function getLastPost()
{
return $this->lastPost;
}
/**
* Set content
*
* #param string $content
* #return Topic
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set forum
*
* #param Forum $forum
* #return Topic
*/
/*public function setForum(\BISSAP\BodyConceptBundle\Entity\Forum $forum)*/
public function setForum(Forum $forum)
{
$this->forum = $forum;
return $this;
}
/**
* Get forum
*
* #return \BISSAP\BodyConceptBundle\Entity\Forum
*/
public function getForum()
{
return $this->forum;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime();
}
/**
* Add posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
* #return Topic
*/
public function addPost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
*/
public function removePost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
User.php
<?php
namespace BISSAP\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* BISSAP\UserBundle\Entity\User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\UserBundle\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
* #var ArrayCollection $Topics
*
* #ORM\OneToMany(targetEntity="\BISSAP\ForumBundle\Entity\Topic", mappedBy="User", cascade={"persist", "remove", "merge"})
*/
private $Topics;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=30, nullable=true)
*/
private $pseudo;
/**
* #ORM\Column(name="name", type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )
*/
private $name;
/**
* #ORM\Column(name="firstname", type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your firstname.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="website", type="string", length=100, nullable=true)
*/
private $website;
/**
* #var string
*
* #ORM\Column(name="avatar", type="string", length=100, nullable=true)
*/
private $avatar;
/**
* #var string
*
* #ORM\Column(name="signature", type="string", length=200, nullable=true)
*/
private $signature;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=100, nullable=true)
*/
private $location;
/**
* #var \DateTime
*
* #ORM\Column(name="registration", type="datetime")
*/
private $registration;
/**
* #var \DateTime
*
* #ORM\Column(name="last_visit", type="datetime")
*/
private $lastVisit;
/**
* #var integer
*
* #ORM\Column(name="rank", type="integer", nullable=true)
*/
private $rank;
/**
* #var integer
*
* #ORM\Column(name="nb_post", type="integer", nullable=true)
*/
private $nbPost;
/**
* #var integer
*
* #ORM\Column(name="nb_topic", type="integer", nullable=true)
*/
private $nbTopic;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set pseudo
*
* #param string $pseudo
* #return User
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set website
*
* #param string $website
* #return User
*/
public function setWebsite($website)
{
$this->website = $website;
return $this;
}
/**
* Get website
*
* #return string
*/
public function getWebsite()
{
return $this->website;
}
/**
* Set avatar
*
* #param string $avatar
* #return User
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set signature
*
* #param string $signature
* #return User
*/
public function setSignature($signature)
{
$this->signature = $signature;
return $this;
}
/**
* Get signature
*
* #return string
*/
public function getSignature()
{
return $this->signature;
}
/**
* Set location
*
* #param string $location
* #return User
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set registration
*
* #param \DateTime $registration
* #return User
*/
public function setRegistration($registration)
{
$this->registration = $registration;
return $this;
}
/**
* Get registration
*
* #return \DateTime
*/
public function getRegistration()
{
return $this->registration;
}
/**
* Set lastVisit
*
* #param \DateTime $lastVisit
* #return User
*/
public function setLastVisit($lastVisit)
{
$this->lastVisit = $lastVisit;
return $this;
}
/**
* Get lastVisit
*
* #return \DateTime
*/
public function getLastVisit()
{
return $this->lastVisit;
}
/**
* Set rank
*
* #param integer $rank
* #return User
*/
public function setRank($rank)
{
$this->rank = $rank;
return $this;
}
/**
* Get rank
*
* #return integer
*/
public function getRank()
{
return $this->rank;
}
/**
* Set nbPost
*
* #param integer $nbPost
* #return User
*/
public function setNbPost($nbPost)
{
$this->nbPost = $nbPost;
return $this;
}
/**
* Get nbPost
*
* #return integer
*/
public function getNbPost()
{
return $this->nbPost;
}
/**
* Set nbTopic
*
* #param integer $nbTopic
* #return User
*/
public function setNbTopic($nbTopic)
{
$this->nbTopic = $nbTopic;
return $this;
}
/**
* Get nbTopic
*
* #return integer
*/
public function getNbTopic()
{
return $this->nbTopic;
}
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->Topics = new \Doctrine\Common\Collections\ArrayCollection();
$this->registration = new \DateTime();
$this->lastVisit = new \DateTime();
}
/**
* Add Topics
*
* #param \BISSAP\ForumBundle\Entity\Topic $topics
* #return User
*/
public function addTopic(\BISSAP\ForumBundle\Entity\Topic $topics)
{
$this->Topics[] = $topics;
return $this;
}
/**
* Remove Topics
*
* #param \BISSAP\ForumBundle\Entity\Topic $topics
*/
public function removeTopic(\BISSAP\ForumBundle\Entity\Topic $topics)
{
$this->Topics->removeElement($topics);
}
/**
* Get Topics
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTopics()
{
return $this->Topics;
}
/**
* Set name
*
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set firstname
*
* #param string $firstname
* #return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
}
I would like to see the request generated by Doctrine but i don't know the way to display it.
So i'm trying to access to pseudo user with {{ forum.topics.last.user.pseudo }}
I get Error:
An exception has been thrown during the rendering of a template ("Notice: Undefined property: BISSAP\ForumBundle\Entity\Topic::$user") in BISSAPForumBundle:F:index-forum.html.twig at line 53.
I moved $User by $user and i get :
Impossible to access an attribute ("user") on a boolean variable ("") in BISSAPForumBundle:F:index-forum.html.twig at line 53
UserRepository::findAllOrderByCategory() doesn't exist but
ForumRepository::findAllOrderByCategory() :
class ForumRepository extends EntityRepository
{
public function findAllOrderByCategory()
{
return $this->createQueryBuilder('p')
->leftJoin('p.Category','c')
->orderBy('c.ordre', 'desc')
->getQuery()
->getResult();
}
}
Doctrine is lazy-loading related objects by default, unless the related object is already loaded. Accessing the related object (i.e. echo-ing Topic.user.pseudo) should trigger loading the full object.
See the footnote at: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#joins
If that doesn't work, could you add a screenshot of the error message and the contents of your UserRepository::findAllOrderByCategory() method in a response?
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.
Excuse me for my English.
I have 3 classes: User, Category and Service.
When I do even a simple query to the database for Service, for example findAll(), my computer hangs... At the same time, the query for Category and User are good.
Thank you for your help!
User.php
namespace General\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your type.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max="255",
* minMessage="The type is too short.",
* maxMessage="The type is too long.",
* groups={"Registration", "Profile"}
* )
*/
protected $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
}
Category.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Category
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #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")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\OneToMany(targetEntity="\General\AnnuaireBundle\Entity\Service", mappedBy="categories")
*/
private $services;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
$this->services = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
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 Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Category
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* #ORM\PrePersist()
*/
public function setCreatedAt($createdAt = null) {
$this->createdAt = null === $createdAt ? new \DateTime() : $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add services
*
* #param \General\AnnuaireBundle\Entity\Service $services
* #return Category
*/
public function addService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services[] = $services;
return $this;
}
/**
* Remove services
*
* #param \General\AnnuaireBundle\Entity\Service $services
*/
public function removeService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services->removeElement($services);
}
/**
* Get services
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServices()
{
return $this->services;
}
}
Service.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\ServiceRepository")
*/
class Service
{
/**
* #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")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToOne(targetEntity="\General\AnnuaireBundle\Entity\Category", inversedBy="services")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $categories;
/**
* #ORM\ManyToOne(targetEntity="\General\UserBundle\Entity\User")
*/
private $users;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Service
*/
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 Service
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Service
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Service
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set categories
*
* #param \General\AnnuaireBundle\Entity\Category $categories
* #return Service
*/
public function setCategories(\General\AnnuaireBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return \General\AnnuaireBundle\Entity\Category
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set users
*
* #param \General\UserBundle\Entity\User $users
* #return Service
*/
public function setUsers(\General\UserBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* #return \General\UserBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
}
Controller.php
public function showServicesAction()
{
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services,
)
);
}
If I modified my function as:
$user = $this->container->get('security.context')->getToken()->getUser();
$user_id = $user->getId();
// var_dump($user_id); ALL IS RIGHT
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
// var_dump($user_id); ALL IS RIGHT
// IF: var_dump($services[0]); COMPUTER HUNGS
// IF: echo count($services); RESPONSE RIGHT
// IF:
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services, ));
// SCREEN WHITE
If you print object in browser it get hanged because symphony object contains lots of info. suppose if you have relation with other tables it will have current tables info as well as other related tables info (Schema, Data, Relationship etc.) as well so it might 99% chance to hanged the browser. Better to print "echo count($services)" to check object exists or not.
Try Debug::dump($service) or any variable - you will be able to see the objects (without the proxy)
i'm receiving the following error message upon persisting and flushing an object with its associations:
Catchable Fatal Error: Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 519 and defined in
.../vendor/doctrine/common/lib/Doctrine/Common/Collections/ArrayCollection.php line 48
what i have is a single table inheritance with this as the base object:
use Doctrine\ORM\Mapping as ORM;
/**
* ObjectData
*
* #ORM\Table(name="object_data")
* #ORM\Entity(repositoryClass="Edexp\CoreBundle\Entity\ObjectDataRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="entity_name", type="string")
* #ORM\DiscriminatorMap({
* "request" = "Edexp\MessageBundle\Entity\RequestData"
* })
* #ORM\HasLifecycleCallbacks
*/
class ObjectData
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var User
*
* #ORM\OneToMany(targetEntity="User", mappedBy="data")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="`key`", type="string", length=255)
*/
private $key;
/**
* #var string
*
* #ORM\Column(name="data", type="blob")
*/
private $data;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return ObjectData
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set user
*
* #param User $user
* #return ObjectData
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User
*/
public function getUser()
{
return $this->user;
}
/**
* Set key
*
* #param string $key
* #return ObjectData
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get key
*
* #return string
*/
public function getKey()
{
return $this->key;
}
/**
* Set data
*
* #param string $data
* #return ObjectData
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return string
*/
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prepareForPersist()
{
$this->created_at = new \DateTime();
}
}
and an additional object that inherits from ObjectData:
use Doctrine\ORM\Mapping as ORM;
use MyProject\CoreBundle\Entity\ObjectData;
/**
* RequestData
*
* #ORM\Entity()
*/
class RequestData extends ObjectData
{
/**
* var Request $request
*
* #ORM\ManyToOne(targetEntity="Request", inversedBy="data")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*/
private $request;
/**
* Set request
*
* #param Request $request
* #return RequestData
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get request
*
* #return Request
*/
public function getRequest()
{
return $this->request;
}
}
and here's the object that utilizes the RequestData entity:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Request
*
* #ORM\Table(name="requests")
* #ORM\Entity(repositoryClass="RequestRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Request
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Message $message
*
* #ORM\ManyToOne(targetEntity="Message", inversedBy="requests")
*/
private $message;
/**
* #var RequestType $type
*
* #ORM\ManyToOne(targetEntity="RequestType")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(
* targetEntity="RequestData",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $data;
/**
* #var datetime $created_at
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var text $comment
*
* #ORM\Column(name="comment", type="text")
*/
private $comment;
/**
* #var ArrayCollection $responses
*
* #ORM\OneToMany(
* targetEntity="Response",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $responses;
public function __construct()
{
$this->data = new ArrayCollection();
$this->responses = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set message
*
* #param Message $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* Get message
*
* #return Message
*/
public function getMessage()
{
return $this->message;
}
/**
* Set type
*
* #param RequestType $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return RequestType
*/
public function getType()
{
return $this->type;
}
/**
* Set created_at
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
}
/**
* Get created_at
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set comment
*
* #param text $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Get comment
*
* #return text
*/
public function getComment()
{
return $this->comment;
}
/**
* Add response
*
* #param Response $response
*/
public function addResponse($response)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $response->getUser() )
return;
}
$this->responses->add($response);
}
/**
* Get responses
*
* #return ArrayCollection
*/
public function getResponses()
{
return $this->responses;
}
public function hasResponse($user)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $user )
return $r;
}
return null;
}
public function addData($data)
{
$data->setRequest($this);
$this->data->add($data);
}
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$this->created_at = new \DateTime();
}
}
and finally the code that results in an error:
use MyProject\MessageBundle\Entity\Request as MyRequest;
$data = new RequestData();
$data->setUser($user);
$data->setKey('user_id');
$data->setData(6);
$req = new MyRequest();
$req->setMessage($message);
$req->setComment('bla');
$req->setType($doctrine->getRepository('MessageBundle:RequestType')->find(1));
$req->addData($data);
$em->persist($req);
$em->flush();
any suggestions as to what might be wrong here?
cheers
so here's what i had to do in order to make it work.
i had to change the association in ObjectData from:
#ORM\OneToMany(targetEntity="User", mappedBy="data")
to
#ORM\ManyToOne(targetEntity="User", inversedBy="data")
added the data field to the User entity accordingly.
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(targetEntity="ObjectData", mappedBy="user")
*/
private $data;
and voila, it worked.
Try:
$req->addData(array($data));
Explanation:
arrayCollection constructor type hints an array as its parameter, so you need to always pass it an array.