I am trying to serialize entities for mobile digest. I have this Entity class:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
/**
* xxx\xxx\Entity\User
*
* #ORM\Table()
* #ORM\Entity()
* #ORM\Entity(repositoryClass="xxx\xxx\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Music", mappedBy="user")
*/
protected $musics;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Message", mappedBy="user")
*/
protected $messages;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Location", mappedBy="user")
*/
protected $locations;
public function __construct()
{
parent::__construct();
$this->musics = new ArrayCollection();
$this->messages = new ArrayCollection();
$this->locations = new ArrayCollection();
}
}
Now when I call this line in my DefaultController.php:
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$array = $em->getRepository('xxxBundle:User')
->findLatest();
$serializer = $this->get('serializer');
$response = $serializer->serialize($array, 'json'); //THIS LINE THROWS EXCEPTION
I have use Doctrine\Common\Collections\ArrayCollection; in DefaultController.php, but it seems the error is coming from inside JMSSerializerBundle.
What have I tried thusfar
I have tried defining the Doctrine annotations to start with a \, but that didn't help
I have cleared my cache a million times
I have searched for similar exceptions, but they all seem to be caused by a typo and I've checked for typos for the last 48 hours and I can't find one.
The classes were autogenerated with app/console.
Take a look at this issue on GitHub: https://github.com/schmittjoh/JMSSerializerBundle/issues/123
This solution works!
I am using JMSSerializerBundle and in Serialized Entity i have ManyToOne relation. I used property $product and of course setter and getter for that. If serializer try to get Product I got this same message i thnk because it don't understand how to convert related Entity to string/int. I adding Accessor with custom method getProductId and inside this method return
$this->product->getId()
JMS\Serializer\Annotation as Serializer
#Serializer\Accessor(getter="getProductId")
In OneToMany relation, in custom get method I return ArrayCollection as Array $this->statuses->toArray()
You can also think of coonverter for relation entity, but I haven't tried (no time)
Related
I am using Symfony3 with doctrine and my question is:
Is possible after getQuery in query builder get results with attribute which has formatted date?
I have attr in entity:
/**
* #var \DateTime
*
* #ORM\Column(name="terminFrom", type="date", nullable=true)
*/
private $terminFrom;
My try - set format in getter:
/**
* #return string
*/
public function getTerminFrom()
{
return $this->terminFrom->format('d.m.Y');
}
But still after getQuery i have \DateTime object in this attribute.
I don't understand - attributes in entity are private so getters must be called... or?
I got three classes:
ProjectType
Phase
ProjectTypePhase (This is to create a seperate join table to make sure ProjectType and Phase gets linked with an id for ordering)
ProjectType
/**
* #OneToMany(targetEntity="ProjectTypePhase", mappedBy="project_type")
*/
private $projectTypePhases;
public function __construct()
{
$this->projectTypePhases = new ArrayCollection();
}
/**
* #return mixed
*/
public function getProjectTypePhases()
{
return $this->projectTypePhases;
}
Phase
/**
* #OneToMany(targetEntity="ProjectTypePhase", mappedBy="phase")
*/
private $projectTypePhases;
public function __construct()
{
$this->projectTypePhases = new ArrayCollection();
}
/**
* #return mixed
*/
public function getProjectTypePhases()
{
return $this->projectTypePhases;
}
ProjectTypePhase
/**
* #ManyToOne(targetEntity="ProjectType", inversedBy="project_type_phase")
* #JoinColumn(name="project_type_id", referencedColumnName="id")
*/
private $projectType;
/**
* #ManyToOne(targetEntity="Phase", inversedBy="project_type_phase")
* #JoinColumn(name="phase_id", referencedColumnName="id")
*/
private $phase;
public function __construct($projectType, $phase)
{
$this->projectType = $projectType;
$this->phase = $phase;
}
I filled the database through MySQL workbench since they are only id entries (correct?). Anyway, whenever I try to do $projectType->getProjectTypePhases();` it returns an empty collection. Also when I try this:
$repository = $this->getDoctrine()->getRepository('AppBundle:ProjectTypePhase');
$projectPhases = $repository->findAll();
I get all the entries, but somehow the variable name for instance of the projecttype and phase entity is null even though they are filled in the database. The corresponding keys are correct and names are filled. What goes wrong? And is there some approach that needs to be done what I am missing? The thing I am trying to accomplish is:
I had a Many to Many relationship which worked fine between ProjectType and Phase. However since there is no id for that table things didn't get in the order I intended to. I had searched for a solution and that was a seperate entity which could handle the relationship between ProjectType and Phase and add additional columns. Is this the correct way?
Modify ProjectTypePhase as follows
/**
* #ManyToOne(targetEntity="ProjectType", inversedBy="projectTypePhases")
* #JoinColumn(name="project_type_id", referencedColumnName="id")
*/
private $project_type;
/**
* #ManyToOne(targetEntity="Phase", inversedBy="projectTypePhases")
* #JoinColumn(name="phase_id", referencedColumnName="id")
*/
private $phase;
You must make names match in order to make the things works. However it's pretty strange that doctrine does not warn you
I have a sql error deploying my symfony project on Unix. Indeed, the query made uses uppercase for table names which was not the case before. In the database, table names are lowercases.
Does anybody know where you configure how you want the queries generation be made (uppercase or lowercase)
Thank you.
Maybe something in Doctrine configuration??
NOTE : I have some new information.
I asked to rebuild my database from the save at a time I know it was working.
I have some errors because, for the new code, the database must be a little different than what it was at this time but I can see that in queries the names of the tables are in lower case.
I pass my new sql (the same as before plus some little changes) in command line.
\. path/to/my/sql
I launch the site and queries are made with table names in uppercase.
Got any idea ?
example of entity :
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MyTable
*
* #ORM\Table(name="mytable")
* #ORM\Entity(repositoryClass="MyBundle\Repository\MyClassRepository")
*/
class MyTable
{
/**
* #var string
*
* #ORM\Column(name="FIELD1, type="string", length=120, nullable=false)
*/
private $field1;
/**
* #var string
*
* #ORM\Column(name="FIELD2", type="string", length=50, nullable=true)
*/
private $field2
/**
* Set field1
*
* #param string $field1
*
* #return Tretb
*/
public function setField1($field1)
{
$this->field1 = $field1;
return $this;
}
/**
* Get field1
*
* #return string
*/
public function getField1()
{
return $this->field1;
}
/**
* Set field2
*
* #param string $field2
*
* #return Tretb
*/
public function setField2($field2)
{
$this->field2 = $field2;
return $this;
}
/**
* Get field2
*
* #return string
*/
public function getField2()
{
return $this->field2;
}
}
Dont know if you can configure it more generally, but you can define table table for each entity with doctrine
/**
* AppBundle\Entity\MyEntity
*
* #ORM\Table()
* #ORM\Entity
* #ORM\Table(name="mytable")
*/
class MyEntity
{
Does your MySQL instance support lowercase tablenames ?
To check the settings use:
mysql> show variables like "lower_case%";
To change the setting you need to change the mysql setting
lower_case_table_names = 1 or lower_case_table_names = 2
Source from Stackoverflow
I am making the lesson administration system on symfony2 and doctrine
I am confused to use foreign key in doctrine.
/Entity/User.php
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*#ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Lesson", inversedBy("teacher"))
*/
protected $id;
.
.
}
/Entity/Lesson.php
class Lesson
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy("id"))
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $teacher;
.
.
}
Each 'Lesson' has one teacher registered in User.php.
How can I write annotation for this purpose?
I am also planning that each Lesson has multiple students from /Entity/User.
How can I write annotation for this purpose? (ManyToMany?)
I have researched ,but I couldn't find good documents for doctrine annotation.
Here some cheat sheets for doctrine annotations : link
For your problem, you need to define your variables in each side of your associations.
In Lesson.php :
/**
* #ORM\OneToOne(
* targetEntity="Acme\UserBundle\Entity\User",
* inversedBy="lessons*removethis : name of the variable in user.php*"
* )
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $teacher;
In User.php :
/**
* #ORM\OneToOne(
* targetEntity="Acme\UserBundle\Entity\Lesson",
* mappedBy="teacher*removethis : name of the variable in lesson.php*"
* )
*/
private $lessons;
And yes, ManyToMany is good for the purpose your are looking for :)
In my Symfony2 project I have two related entities: Users and Favorites. They have a many-to-many relationship.
My application works as follows:
In my Twig-page I have an few items with a button 'Add to Favorites'. When you click the button my controller saves the item_id in the Favorites column. But then I want to save
the user who added the item to his favorites and here my application fails.
The User and the favorite exist but the joincolumn between Users and Favorites remains empty.
I also don't receive any kind of errors.
Here is my code:
Entity Users
class Users implements AdvancedUserInterface
{
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
* #ORM\JoinTable(name="user_has_favorite",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="favorite_id", referencedColumnName="favorite_id")
* }
* )
*/
private $favorite;
public function __construct()
{
$this->favorite = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addFavorite(\Geo\CityTroopersBundle\Entity\Favorites $favorite)
{
$this->favorite[] = $favorite;
return $this;
}
...
Entity Favorites
class Favorites
{
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Users", mappedBy="favorite", cascade={"persist"})
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addUser(\Geo\CityTroopersBundle\Entity\Users $user)
{
$this->user[] = $user;
return $this;
}
My controller
public function showNewsAction()
{
$request = $this->get('request');
$itemId=$request->request->get('itemId');
if($itemId != NULL)
{
//MAKE NEW FAVORITE AND ADD TO DATABASE LINKED WITH ITEM
$favorite = new Favorites();
$favorite->setItemId($itemId);
//LINK FAVORITE ID WITH USER ID IN JOINCOLUMN
$userId = 6;
$em = $this->getDoctrine()->getEntityManager();
$user = $em->getRepository('GeoCityTroopersBundle:Users')->find($userId);
$favorite->addUser($user);
$em->persist($favorite);
//I TRIED THIS TOO, BUT IT FAILED
/*$user->addFavorite($favorite);
$em->persist($user);*/
$em->flush();
You were close there. For doctrine many-to-many relationships, you need to call both add methods
$favorite->addUser($user);
$user->addFavorite($favorite);
$em->persist($favorite);
$em->persist($user);
$em->flush();
This should do the trick. In the docs they do this, but don't mention it too explicitly. Not sure why either because lots of people run into this (myself included).
As explained here, only the owning side is responsible for the connection management :
http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association
So only
$user->addFavorite($favorite);
should persist, and not
$favorite->addUser($user);
Like indicated by Cedric, adding a record for a many to many relation is done only in one direction and it depends on how you defined the relation: adding can be done only by the parent entity of the relation, so in your case you must use:
$user->addFavorite($favorite);
In your line :
#ORM\JoinColumn(name="favorite_id", referencedColumnName="favorite_id")
The
name="favorite_id"
part refers to the columns in the join table, whereas the
referencedColumnName="favorite_id"
refers to the id in the favorite table which usualy is simply "id". You should try :
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
* #ORM\JoinTable(name="user_has_favorite",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="favorite_id", referencedColumnName="id")
* }
* )
*/
private $favorite;