I would like to save my users search on my website. Thaht's why i have a Class User and i would like to create Search Class.
I have done that :
class Search
{
public function __construct()
{
$this->searched_date = new \Datetime();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="test\UserBundle\Entity\User")
*/
private $user;
/**
* #ORM\Column(name="termsearch", type="string", length=255, nullable="true")
*/
private $termsearch;
/**
* #ORM\Column(name="goodtitle", type="string", length=255, nullable="true")
*/
private $goodtitle;
/**
* #ORM\Column(name="searched_date", type="datetime")
*/
private $searched_date;
/**
* Set termsearch
*
* #param text $termsearch
*/
public function setTermsearch($termsearch)
{
$this->termsearch = $termsearch;
}
/**
* Get termsearch
*
* #return text
*/
public function getTermsearch()
{
return $this->termsearch;
}
/**
* Set searched_date
*
* #param datetime $searchedDate
*/
public function setSearchedDate($searchedDate)
{
$this->searched_date = $searchedDate;
}
/**
* Get searched_date
*
* #return datetime
*/
public function getSearchedDate()
{
return $this->searched_date;
}
/**
* Set user
*
* #param test\UserBundle\Entity\User $user
*/
public function setUser(\test\UserBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return test\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set goodtitle
*
* #param text $goodtitle
*/
public function setGoodtitle($goodtitle)
{
$this->goodtitle = $goodtitle;
}
/**
* Get goodtitle
*
* #return text
*/
public function getGoodtitle()
{
return $this->goodtitle;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
And i would like to insert like that :
$em = $this->getDoctrine()->getEntityManager();
$user = $em->getRepository('TestUserBundle:User')->find($currentuser->getID());
$search = new Search();
$search->setUser($user);
$search->setTermsearch($termsearch);
$search->setGoodtitle($goodtitle);
$em->persist($search);
$em->flush();
Unfortunately i have this error :
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens (500 Internal Server Error)
And in the stack we can found that :
INSERT INTO s_search (user_id, termsearch, goodtitle, searched_date) VALUES (?, ?, ?, ?) ({"1":"c2c","2":"C2C Down The Road","3":{"date":"2012-10-31 00:18:47","timezone_type":3,"timezone":"Europe\/Paris"}})
I don't know how i can create this class Search...
Thank for for you help !
Remove #ORM\Id from the $user as #ManyToOne mapping reference does not require a type. See Doctrine's Annotation Reference for details. Doctrine takes care of the correct column type to hold the reference to another entity.
Make also sure that your User query really returns a valid $user. If it's possible that Search does not have $user, use #JoinColumn annotation to claim the column nullable. See another SO question Doctrine 2 can't use nullable=false in manyToOne relation?
Related
I have two entities:
TicketEntity :
/**
* #ORM\MappedSuperclass()
*/
class Ticket implements TicketInterface
{
const DIR_UPLOAD = 'TicketUpload';
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Attachment", mappedBy="ticket", cascade={"remove"}, orphanRemoval=true)
*/
protected $attachments;
/**
* Ticket constructor.
*/
public function __construct()
{
$this->attachments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* Add attachments
*
* #param Attachment $attachments
* #return Ticket
*/
public function addAttachment(Attachment $attachments)
{
$this->attachments[] = $attachments;
return $this;
}
/**
* Remove attachments
*
* #param Attachment $attachments
*/
public function removeAttachment(Attachment $attachments)
{
$this->attachments->removeElement($attachments);
}
/**
* Get attachments
*
* #return Collection
*/
public function getAttachments()
{
return $this->attachments;
}
}
AttachmentEntity:
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\AttachmentRepository")
* #ORM\Table(name="ticket_attachments")
*/
class Attachment
{
const DIR_UPLOAD = 'TicketUpload';
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
* #ORM\Column(type="text", nullable=true)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Ticket", inversedBy="attachments")
* #ORM\JoinColumn(name="ticket_id", referencedColumnName="id", nullable=true)
*/
protected $ticket;
/**
* #Assert\File(
* maxSize = "300k",
* mimeTypes = {"application/pdf", "application/x-pdf", "text/plain", "application/msword",
* "application/vnd.ms-excel", "image/jpeg", "image/x-citrix-jpeg", "image/png", "image/x-citrix-png", "image/x-png", "image/gif"},
* mimeTypesMessage = "Liste de formats de fichiers acceptés : .pdf,.txt,.doc,.xls,.jpg,.png,.gif"
* )
*/
private $attachmentFile;
/**
* #ORM\Column(type="string", nullable=true)
*
*/
private $attachment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name): self
{
$this->name = $name;
return $this;
}
public function getTicket(): ?Ticket
{
return $this->ticket;
}
public function setTicket(Ticket $ticket): void
{
$this->ticket = $ticket;
}
/**
* #return mixed
*/
public function getAttachment(): ?string
{
return $this->attachment;
}
public function setAttachment($attachment): self
{
$this->attachment = $attachment;
return $this;
}
public function getAttachmentFile(): ?UploadedFile
{
return $this->attachmentFile;
}
/**
* #param $attachmentFile
* #return Ticket
*/
public function setAttachmentFile($attachmentFile): self
{
$this->attachmentFile = $attachmentFile;
return $this;
}
public function getAttachmentWebPath()
{
return self::DIR_UPLOAD . '/' . $this->getAttachment();
}
}
My goal is that a ticket can have several attachments.
And I have this error:
The association AppBundle\Entity\Attachment#ticket refers to the
inverse side field AppBundle\Entity\Ticket#attachments which does not
exist.
I don't know where I'm wrong... Anyone know ?
Regards
mapped superclasses are really inconvenient. really. (emphasis mine)
A mapped superclass cannot be an entity, it is not query-able and
persistent relationships defined by a mapped superclass must be
unidirectional (with an owning side only). This means that One-To-Many
associations are not possible on a mapped superclass at all.
Furthermore Many-To-Many associations are only possible if the mapped
superclass is only used in exactly one entity at the moment. For
further support of inheritance, the single or joined table inheritance
features have to be used.
so, you're not technically doing something wrong, it just isn't supported at all. The error message produced isn't helpful at all though...
I have two entities in my code: Session and SessionPicture.
There is a OneToOne relationship between Session and SessionPicture. SessionPicture is the mapping entity and Session is the inverse one.
Session has an attribute called "Slug", which is generated thanks to the StofDoctrineExtensionsBundle https://github.com/stof/StofDoctrineExtensionsBundle, and using the Gedmo\Sluggable annotation.
I have a form to create a Session (so a SessionType), and this SessionType embeds a SessionPictureType. The SessionPicture class contains a file attribute (UploadedFile class) and I have used LifecycleEvents (PostPersist/PostUpdate) to upload the file of the SessionPicture, and give it the "slug" property of the related Session when I save it.
My issue is that when I try to change another property of my SessionPicture (let's say "alt") and give it the value of the "slug" of the session , I cannot do it in the PostPersist Lifecycle and then save it to my database, because this event takes place after the onFlush, which is too late. I have to do it in the PrePersist Lifecyle. But then the "slug" of my session is not available yet, because it is generated during the onFlush by the extension.
So how can I get the slug of the related session in the prePersist lifecyle?
(PS: I have a found a solution, which is to persist the session in my controller, flush with the Manager, and then to persist again and redo a flush() but it is not very elegant).
Please find my code below:
/**
* Session
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Session
{
/**
* #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, nullable=false)
*/
private $name;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\SessionPicture", cascade={"persist", "remove"}, mappedBy="session")
* #ORM\JoinColumn(name="session_picture_id", referencedColumnName="id", nullable=true)
*/
private $sessionPicture;
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sessionPicture
*
* #param \MyBundle\Entity\SessionPicture $sessionPicture
*
* #return Session
*/
public function setSessionPicture(MyBundle\Entity\SessionPicture $sessionPicture = null)
{
$this->sessionPicture = $sessionPicture;
return $this;
}
/**
* Get sessionPicture
*
* #return \MyBundle\Session\SessionPicture
*/
public function getSessionPicture()
{
return $this->sessionPicture;
}
And my SessionPicture code:
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255, nullable=true)
*/
private $alt;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\Session", inversedBy="sessionPicture")
*/
private $session;
public $file;
private $fileNameForRemove;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set extension
*
* #param string $extension
*
* #return SessionPicture
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set alt
*
* #param string $alt
*
* #return SessionPicture
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* Set path
*
* #param string $path
*
* #return SessionPicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set session
*
* #param \MyBundle\Entity\Session $session
*
* #return SessionPicture
*/
public function setSession(\NyBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \MyBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$this->extension = (string)$extension;
My issue is below, I cannot get the slug before the flush of the session
$this->alt = $this->getSession()->getSlug();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
But here, I can get the slug because my session has already been flushed and the slug generated
$this->alt = $this->getSession()->getSlug();
$this->path = $this->alt.'.'.$this->extension;
if ($this->file === null)
return ;
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
Finally, here is an extract my controller code:
$form->handlerequest($request);
$validator = $this->get('validator');
$errorList = $validator->validate($session);
if (count($errorList) == 0)
{
$em = $this->getDoctrine()->getManager();
$em->persist($session);
$em->flush();
$em->persist($session);
$em->flush();
As you can see, I had to persist the $session and to flush it once, so that the slug is generated at the flush. Then persist again so that the slug is now available for the "alt" property of the SessionPicture at the prePersist n2, and flush again to save the alt property. But it is not very clean.
Thanks for any hel or advice. Thanks.
I've created an Entity to store some data i'm pulling via an api
When i try to findByOne to see if the entry already exists, i get an error saying the field is not recognised.
I've done a php app/console doctrine:schema:update --force
I can see the table in my mySQL manager with the right fieldname 'StadiumID'
So why cant doctrine find it when i do findByOne();
My Entity Class:
<?php
namespace FantasyPro\DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stadium
*
* #ORM\Table("fp_stadium")
* #ORM\Entity(repositoryClass="FantasyPro\DataBundle\Entity\StadiumRepository")
*/
class Stadium
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="StadiumID", type="integer", length=2, nullable=false, unique=true)
*/
private $stadiumID;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=100, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="City", type="string", length=50, nullable=false)
*/
private $city;
/**
* #var string
*
* #ORM\Column(name="State", type="string", length=10, nullable=true)
*/
private $state;
/**
* #var string
*
* #ORM\Column(name="Country", type="string", length=2, nullable=false)
*/
private $country;
/**
* #var integer
*
* #ORM\Column(name="Capacity", type="integer", length=32, nullable=true)
*/
private $capacity;
/**
* #var string
*
* #ORM\Column(name="PlayingSurface", type="string", length=50, nullable=true)
*/
private $playingSurface;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set stadiumID
*
* #param integer $stadiumID
* #return Stadium
*/
public function setStadiumID($stadiumID)
{
$this->stadiumID = $stadiumID;
return $this;
}
/**
* Get stadiumID
*
* #return integer
*/
public function getStadiumID()
{
return $this->stadiumID;
}
/**
* Set name
*
* #param string $name
* #return Stadium
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set city
*
* #param string $city
* #return Stadium
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set state
*
* #param string $state
* #return Stadium
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string
*/
public function getState()
{
return $this->state;
}
/**
* Set country
*
* #param string $country
* #return Stadium
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set capacity
*
* #param integer $capacity
* #return Stadium
*/
public function setCapacity($capacity)
{
$this->capacity = $capacity;
return $this;
}
/**
* Get capacity
*
* #return integer
*/
public function getCapacity()
{
return $this->capacity;
}
/**
* Set playingSurface
*
* #param string $playingSurface
* #return Stadium
*/
public function setPlayingSurface($playingSurface)
{
$this->playingSurface = $playingSurface;
return $this;
}
/**
* Get playingSurface
*
* #return string
*/
public function getPlayingSurface()
{
return $this->playingSurface;
}
}
The code i'm using to add the data if it does not exist and to update it if it does exist:
<?php
namespace FantasyPro\DataBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FantasyPro\DataBundle\Entity\Stadium;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('DataBundle:Default:index.html.twig', array('name' => $name));
}
public function updateStadiumAction(){
//get list of stadiums
$client = $this->container->get('fantasyapi');
$stadiumData = $client->Stadiums();
//var_dump($stadiumData);
//get the entity manager
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DataBundle:Stadium');
$log = $stadiumData;
foreach($stadiumData as $stadium){
// Get the current stadium in the list
$criteria = array("StadiumID" =>$stadium['StadiumID']);
var_dump($criteria);
$storedStadium = $repo->FindOneBy($criteria);
if (!$storedStadium) {
/* throw $this->createNotFoundException(
'No product found for id '.$stadium['StadiumID']
);*/
//no stadium exists with the StadiumID passed
//create a new entry
$entry = new Stadium();
$entry->setStadiumID($stadium['StadiumID']);
$entry->setName($stadium['Name']);
$entry->setCity($stadium['City']);
$entry->setState($stadium['State']);
$entry->setCountry($stadium['Country']);
$entry->setCapacity($stadium['Capacity']);
$entry->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($entry);
$log .= 'Added New Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}else{
$storedStadium->setStadiumID($stadium['StadiumID']);
$storedStadium->setName($stadium['Name']);
$storedStadium->setCity($stadium['City']);
$storedStadium->setState($stadium['State']);
$storedStadium->setCountry($stadium['Country']);
$storedStadium->setCapacity($stadium['Capacity']);
$storedStadium->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($storedStadium);
$log .= 'Updated Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}
}
//$em->flush();
return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));
}
}
The property name is actually:
private $stadiumID;
So you should do :
$repo->findOneBy(array('stadiumID' => $value));
so change this row:
$criteria = array("StadiumID" =>$stadium['StadiumID']);
to this:
$criteria = array("stadiumID" =>$stadium['StadiumID']);
Doctrine's main role is to connect your application layer(entites) to the database layer(tables). So doctrine tries to translate request comming from the application layer to the database. Even if you named your field in the database "StadiumID"or "table_name_snake_case", when you call findOneBy(array($property => $value)), doctrine expects $property to refer to the property name, and it will translate this to SQL to something like 'SELECT FROM .... where StadiumID = :value'
For others who still have the problem,
make sur that you have puted the sign '=>' instead of ',' when calling the function findOneBy(...)
So instead of :
findOneBy(["code" , "Code-Example"]);
do that :
findOneBy(["code" => "Code-Example"]);
Also, make sure the doctrine naming strategy is specified:
doctrine:
orm:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
this is the doctrine's default naming strategy. This way doctrine knows how to map Entity property names to column names.
Note that, naming strategy configuration might be in different levels of doctrine configuration. For example, in another repo it is configured like this:
doctrine:
orm:
default_entity_manager: shopping
entity_managers:
shopping:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
why Symfony2 performs 40 DB queries if I use following code:
$em = $this->getDoctrine()->getManager();
$records = $em->getRepository('MyWebBundle:Highlight')->findAll();
I thought that findAll() method returns only all items from Highlight entity and associations to other entities replaces Proxy objects. But now findAll() method gettings all associations entities.
Do you know where is the problem ?
indexAction
public function indexAction() {
$em = $this->getDoctrine()->getManager();
$records = $em->getRepository('MyWebBundle:Highlight')->findAll();
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken(self::FORM_TOKEN_ID);
$params = array(
"data" => array(
"all" => $records,
),
"token" => $token->getValue(),
"static" => array(
"add" => $this->generateUrl("admin_highlight_add"),
"edit" => $this->generateUrl("admin_highlight_edit"),
"del" => $this->generateUrl("admin_highlight_del"),
),
);
$ser = $this->get('jms_serializer');
$jsonContent = $ser->serialize($params, 'json');
return array('jsonContent' => $jsonContent);
}
Highlight entity
namespace My\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
/**
* Highlight
*
* #JMS\ExclusionPolicy("none")
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\WebBundle\Entity\HighlightRepository")
*/
class Highlight {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="abbreviation", type="string", length=8, unique=true)
*/
private $abbreviation;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=80, nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="color", type="string", length=7)
*/
private $color;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="Goods", mappedBy="highlight")
*/
private $goods;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="Calibration", mappedBy="highlight")
*/
private $calibrations;
/**
* Constructor
*/
public function __construct() {
$this->goods = new \Doctrine\Common\Collections\ArrayCollection();
$this->calibrations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set abbreviation
*
* #param string $abbreviation
* #return Highlight
*/
public function setAbbreviation($abbreviation) {
$this->abbreviation = $abbreviation;
return $this;
}
/**
* Get abbreviation
*
* #return string
*/
public function getAbbreviation() {
return $this->abbreviation;
}
/**
* Set description
*
* #param string $description
* #return Highlight
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* Set color
*
* #param string $color
* #return Highlight
*/
public function setColor($color) {
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return string
*/
public function getColor() {
return $this->color;
}
/**
* Add goods
*
* #param \My\WebBundle\Entity\Goods $goods
* #return Highlight
*/
public function addGood(\My\WebBundle\Entity\Goods $goods) {
$this->goods[] = $goods;
return $this;
}
/**
* Remove goods
*
* #param \My\WebBundle\Entity\Goods $goods
*/
public function removeGood(\My\WebBundle\Entity\Goods $goods) {
$this->goods->removeElement($goods);
}
/**
* Get goods
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGoods() {
return $this->goods;
}
/**
* Add calibrations
*
* #param \My\WebBundle\Entity\Calibration $calibrations
* #return Highlight
*/
public function addCalibration(\My\WebBundle\Entity\Calibration $calibrations) {
$this->calibrations[] = $calibrations;
return $this;
}
/**
* Remove calibrations
*
* #param \My\WebBundle\Entity\Calibration $calibrations
*/
public function removeCalibration(\My\WebBundle\Entity\Calibration $calibrations) {
$this->calibrations->removeElement($calibrations);
}
/**
* Get calibrations
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCalibrations() {
return $this->calibrations;
}
}
Highlight repository is empty
I think the problem comes from the serializer. Since you serializer highliths, each of them has their properties serialized as well which means that lazy query will be performed to retieved Goods which will be also serialized.
You should then prevent this behaviour by adding annotations to highlight's goods property as this
use ...
use JMS\SerializerBundle\Annotation\ExclusionPolicy;
use JMS\SerializerBundle\Annotation\Exclude;
/**
* ...
* #ExclusionPolicy("none")
*/
class Highlight
{
/**
* ...
* #Exclude
*/
private $goods;
}
You can have further details about exclusion stratigies from JMSSerializer doc
findAll itself does not perform many queries. Queries are executed when you access related entity via getters. As relation are not fetched eagerly, they first time are fetched when you are acessing them.
I think serializer access all children to send your object.
See Doctrine documentation
Whenever you have a managed entity instance at hand, you can traverse
and use any associations of that entity that are configured LAZY as if
they were in-memory already. Doctrine will automatically load the
associated objects on demand through the concept of lazy-loading.
To prevent this either disable children serialization or use fetch EAGER or build a DQL query, which prefetch all the children alongside with parents, like (just sample, not valid DQL)
SELECT Highlight, Good, Calibration
FROM Highlights Highlight
LEFT JOIN Highlight.googs Good
LEFT JOIN Goog.calibrations Calibration
WHERE ...
I have a problem while json_encodeing a Entity.
public function jsonvoteAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('KorumAGBundle:AGVote')->findOneById($id);
$response = new Response(json_encode($entity, 200));
$response->headers->set('Content-Type',' application/json');
return $response;
}
This code returns me a the users entity
{"users":{"__isInitialized__":false,"id":null,"nickname":null,"pwd":null,"email":null,"firstname":null,"lastname":null,"poste":null,"addr1":null,"addr2":null,"pc":null,"country":null,"phone":null,"province":null,"acess":null,"site":null,"crew":null,"utilisateur":null}}
And when I var dymp my $entity, it returns both my AGVote and USers entity.
Here is my AGVote Entity
<?php
namespace Korum\AGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Korum\AGBundle\Entity\AGVote
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class AGVote
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $question;
/**
* #ORM\Column(type="smallint")
*/
private $actif;
/**
* #ORM\ManyToOne(targetEntity="\Korum\KBundle\Entity\Users", cascade={"all"})
*/
public $users;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set question
* Nb : Only AG admin can set a question
* #param text $question
*/
public function setQuestion($question)
{
$this->question = $question;
}
/**
* Get question
*
* #return text
*/
public function getquestion()
{
return $this->question;
}
/**
* Set actif
*
* #param smallint $actif
*/
public function setActif($actif)
{
$this->actif = $actif;
}
/**
* Get actif
*
* #return smallint
*/
public function getActif()
{
return $this->actif;
}
/**
* Set Users
*
* #param Korum\KBundle\Entity\Province $Users
*/
public function setUsers(\Korum\KBundle\Entity\Users $users)
{
$this->users = $users;
}
/**
* Get Users
*
* #return Korum\KBundle\Entity\Users
*/
public function getUsers()
{
return $this->users;
}
}
Does anyone have an idea of what happened ?
I tried to install the JSMSerializerBundle but event with Metadata library at version 1.1.
When I want to clear my cache, it failed with error :
See :
JMSSerializerBundle Installation : Catchable Fatal Error: Argument 1 passed to JMSSerializerBundle\Twig\SerializerExtension::__construct()
By default, json_encode only uses public properties.
So it serialized the only public property of AGVote: $users. The content of $users was an instance of User; which public fields were serialized.
You could work around these by adding a toArray() method to your entities, and then doing json_encode($entity->toArray()), but i highly recommend you to have a look and use the JMSSerializedBundle.