I am trying to connect 2 entities and I am having troubles with it.
I have two classes: User and Gender.
Each User is from a kind gender (male or female). At my database I have two tables with this structure:
user(**id**, firstName, gender);
gender(**id**, type);
Now I have created two entities at my system. User.php and Gender.php
User
<?php
/**
* #Entity #Table(name="User")
**/
class User
{
/**
* #Id #Column(type="integer") #GeneratedValue
**/
private $id;
/**
* #Column(type="string")
**/
private $firstName;
/**
* #Column(type="string")
* #ManyToOne(targetEntity="Gender")
* #JoinColumn(name="type", referencedColumnName="type")
* #var Gender[]
**/
private $gender;
public function __construct($content) {
$this->setContent($content);
}
/**
* #return int
*/
public function getId() {
return $this->id;
}
/**
* #return string
*/
public function getFirstName() {
return $this->firstName;
}
/**
* #return int
*/
public function getGender() {
return $this->gender;
}
/**
* #param string $content
*/
public function setFirstName($content) {
$this->firstName = (string) $content;
}
/**
* #param string $content
*/
public function setGender($content) {
$this->gender = (string) $content;
}
}
Gender
<?php
/**
* #Entity #Table(name="Gender")
**/
class Gender
{
/**
* #Id #Column(type="integer") #GeneratedValue
**/
private $id;
/**
* #OneToMany(targetEntity="User", inversedBy="gender")
* #JoinColumn(name="gender", referencedColumnName="gender")
* #Column(type="string")
**/
private $type;
/**
* #param integer $content
*
*/
public function getId() {
return $this->id;
}
/**
* #param string $content
*
*/
public function getType() {
return $this->type;
}
/**
* #param string $content
*/
public function setGender($content) {
$this->gender = (string) $content;
}
}
What I want is to get the gender type when I get a User, so both entities have to be connected by gender-type attributes.
I have tried to do so with #ManyToOne or #JoinColumn features, but I couldn't get it.
How can I do it? What I am doing wrong?
Thanks!
Replace this in User Class:
* #JoinColumn(name="type", referencedColumnName="type")
with that :
* #JoinColumn(name="gender", referencedColumnName="type")
Your field name is gender, not type in User table.
In Gender class use only:
* #OneToMany(targetEntity="User", mappedBy="gender")
Might be offtopic but Gender table is useless. You will always have just 2 (male/female) so no point in doing this.
You should create new column in User table, type=integer and use 0/1 for gender. Use constants like
Class User
{
const MALE=0 ;
const FEMALE=1 ;
.... ORM definition...
public function isMale()
{
return $this->getGender() == self::MALE ;
}
And in controller:
if ( !$user->isMale() ) {
.... buy shoes ....
} else {
.... buy beer ....
}
Or similar. Because you only have 2 options, only one function is needed.
You have to join the gender relation if you want to get if from the query.
$dql = "SELECT a,g FROM user a LEFT JOIN a.gender g";
$query = $em->createQuery($dql);
$query->setMaxResults(30);
$users = $query->getResult();
Related
I am new with Symfony. I am working with version 3. I simplified my example. I have 3 Tables, for this tables I created a class for each one.
Table "Person": id | name
Table "Group": id | groupname
Table "PersonGroup": id | person | group
Every Person could be in several groups and every groups can have several persons. In the table PersonGroup I connect the persons with the groups. In my Controller I want to request in which group the selected person is. But in the Dump I only have the data from the PersonGroup table and not the details from the Group (in this example the name):
PersonGroup {#485 ▼
-id: 5
-person: Person {#456 ▼
-id: 4
-name: "Adam"
-personGroups: PersistentCollection {#445 ▶}
}
-group: Group {#486 ▼
+__isInitialized__: false
-id: 5
-name: null
-personGroups: null
…2
}
}
My Controller:
/**
* #Route("/person/{personId}", name="personController")
*/
public function showAction($personId)
{
$em = $this->getDoctrine()->getManager();
$item = $em->getRepository('AppBundle:Person')
->findOneBy(['id' => $personId]);
foreach ($person->getPersonGroup() as $personGroup) {
dump($personGroup);
}
return $this->render('person/detail.html.twig', [
'person' => $person
]);
}
Person class / entity:
class Person
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\PersonGroup", mappedBy="person")
*/
private $personGroups;
/**
* Item constructor.
*/
public function __construct()
{
$this->personGroups= new ArrayCollection();
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return ArrayCollection*
*/
public function getPersonGroups()
{
return $this->personGroups;
}
}
Group class/Entity:
class Group
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\PersonGroup", mappedBy="group")
*/
private $personGroups;
/**
* Item constructor.
*/
public function __construct()
{
$this->personGroups= new ArrayCollection();
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return ArrayCollection*
*/
public function getPersonGroups()
{
return $this->personGroups;
}
}
PersonGroup class / entity:
class PersonGroup
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Person", inversedBy="group")
* #ORM\JoinColumn(nullable=false)
*/
private $person;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Group", inversedBy="person")
* #ORM\JoinColumn(nullable=false)
*/
private $group;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return Person
*/
public function getPerson()
{
return $this->person;
}
/**
* #param Person $person
*/
public function setPerson(Person $person)
{
$this->person = $person;
}
/**
* #return Group
*/
public function getGroup()
{
return $this->group;
}
/**
* #param Group $group
*/
public function setGroup(Group $group)
{
$this->group = $group;
}
}
You can access to your Group entity from PersonGroup
/**
* #Route("/person/{personId}", name="personController")
*/
public function showAction($personId)
{
$em = $this->getDoctrine()->getManager();
$item = $em->getRepository('AppBundle:Person')
->findOneBy(['id' => $personId]);
foreach ($person->getPersonGroup() as $personGroup) {
dump($personGroup->getGroup());
}
return $this->render('person/detail.html.twig', [
'person' => $person
]);
}
But you should create a custom function in Group repository and Person repository to retrieve the correct entity.
EDIT
If you want te retrieve all the Group entity you should add a parameter fetch="EAGER" to your relations, it will automatically do aan innerJoin on your relation.
class PersonGroup
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Person", inversedBy="group", fetch="EAGER")
* #ORM\JoinColumn(nullable=false)
*/
private $person;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Group", inversedBy="person", fetch="EAGER")
* #ORM\JoinColumn(nullable=false)
*/
private $group;
For example if you want to get All Groups from a Person you can do a custom repository function.
Ex:
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Person;
/**
* GroupRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class GroupRepository extends \Doctrine\ORM\EntityRepository
{
public function findByPerson(Person $person){
return $this->createQueryBuilder('g')
->leftJoin('g.personGroups', 'pg')
->leftJoin('pg.person', 'p')
->where('p.id = :personId')
->setParameter('personId', $person->getId())
->getQuery()->getResult();
}
}
I have an application with Zend Framework2 and Doctrine2 as ORM.
I have this Entity called User:
namespace Adm\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User{
/**
* #ORM\Id
* #ORM\Column(type="integer");
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\Column(type="string")
*/
protected $email;
/**
* #ORM\Column(type="string")
*/
protected $password;
/**
* #ORM\ManyToMany(targetEntity="Module")
* #ORM\JoinTable(
* name="user_module",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="module_id", referencedColumnName="id")}
* )
*/
protected $modules;
public function __construct() {
$this->modules = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return the $id
*/
public function getId() {
return $this->id;
}
/**
* #return the $name
*/
public function getName() {
return $this->name;
}
/**
* #return the $email
*/
public function getEmail() {
return $this->email;
}
/**
* #return the $password
*/
public function getPassword() {
return $this->password;
}
/**
* #param field_type $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #param field_type $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* #param field_type $email
*/
public function setEmail($email) {
$this->email = $email;
}
/**
* #param field_type $password
*/
public function setPassword($password) {
$this->password = $password;
}
/**
* Add module
*
* #param dm\Entity\Module
* #return User
*/
public function addModules(Module $modules = null){
$this->modules[] = $modules;
}
/**
* Get modules
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getModules(){
return $this->modules;
}
}
See the modules property is a relation Many to Many with a table called user_modules.
And i have the Entity Module as well:
namespace Adm\Entity;
use Doctrine\ORM\Mapping as ORM;
class Module{
/**
* #ORM\Id
* #ORM\Column(type="integer");
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Column(type="integer")
*/
private $status;
/**
* #return the $id
*/
public function getId() {
return $this->id;
}
/**
* #return the $name
*/
public function getName() {
return $this->name;
}
/**
* #return the $status
*/
public function getStatus() {
return $this->status;
}
/**
* #param field_type $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #param field_type $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* #param field_type $status
*/
public function setStatus($status) {
$this->status = $status;
}
}
I receive a array variable containing the Post from a form to insert in a table. Each post element have it's property in Entity, as expected. Together, i have a $module variable which is an array containing id's of the modules. My question is: How do i insert this data in the user_module table?
My add function is this:
public function addUser($newUser){
$user = new User();
$user->setName($newUser['name']);
...
$this->getEm()->persist($user);
$this->getEm()->flush();
}
Firstly you need to have cascade={"persist"} as mentioned by #skrilled.
Then you need to retrieve the module entities from the database. You mentioned you have the id's in the $module variable.
You need a DQL statement something like this
$builder = $this->getEntityManager()->createQueryBuilder();
$builder->select('m')
->from('Adm\Entity\Module', 'm')
->where('m.id IN (:modules)')
->setParameter('modules', $modules);
$moduleEntities= $builder->getQuery()->getResult(Query::HYDRATE_OBJECT);
and in your User entity you will need
public function addModules(Array $moduleEntities)
{
foreach ($moduleEntities as $module) {
if ($module instanceof Module) {
$this->modules[] = $module;
}
}
return $this;
}
finally in your addUser method you will need to add the array of modules from the above DQL
public function addUser($newUser, $moduleEntities)
{
$user = new User();
$user->setName($newUser['name']);
....
$user->addModules($moduleEntities);
$this->getEm()->persist($user);
$this->getEm()->flush();
}
I hope this helps
You should read about using cascade. This will allow you to save/modify/remove the associated relationships and how you expect this to work.
In this case, you would want the relationship to persist since you want the associated entities to be saved when user itself is saved.
#ORM\ManyToMany(targetEntity="Module", cascade={"persist"})
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html
By default, no operations are cascaded.
The following cascade options exist:
persist : Cascades persist operations to the associated entities.
remove : Cascades remove operations to the associated entities.
merge : Cascades merge operations to the associated entities.
detach : Cascades detach operations to the associated entities.
refresh : Cascades refresh operations to the associated entities.
all : Cascades persist, remove, merge, refresh and detach operations to associated entities.
I have two tables "RFQ" and "RFQitem". I can make form which can create RFQ with their title description and amount. And I can create RFQitem form which can create RFQitem with their title, description and amount.
Problems starts when I need to upgrade my RFQ form, so that I can make in it RFQitems which will saves in their table, but it need to be assigned to RFQ.
In symfony documentation is great example which actually works for me, but this is example is with task and their tags. So task there is with more than one attributes (name, description), but tags are only with one - name.
My RFQ entity with RFQItems looks like this:
/**
* #ORM\ManyToMany(targetEntity="RFQItem", cascade={"persist"})
* #ORM\JoinTable(name="rfq_item_title",
* joinColumns={#ORM\JoinColumn(name="rfq_item_title", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id", referencedColumnName="id")}
* )
*/
protected $rfq_item_title;
/**
* #ORM\ManyToMany(targetEntity="RFQItem", cascade={"persist"})
* #ORM\JoinTable(name="rfq_item_description",
* joinColumns={#ORM\JoinColumn(name="rfq_item_description", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id", referencedColumnName="id")}
* )
*/
protected $rfq_item_description;
/**
* #ORM\ManyToMany(targetEntity="RFQItem", cascade={"persist"})
* #ORM\JoinTable(name="rfq_item_amount",
* joinColumns={#ORM\JoinColumn(name="rfq_item_description", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id", referencedColumnName="id")}
* )
*/
protected $rfq_item_amount;
But I know that this is wrong, but how I make ManyToMany relation with RFQitem which have more than one attributes?
The best way to go is to have this two entities as you are actually doing, the father and the collection childs with the attributtes you like, but do not get fixated to the Symfony example. It's a theoretical OOP, has not relations defined, so I'm going to make my best try to paste a coherent example based on a Theater->Works collection:
class Theater
{
private $name;
private $id;
/**
* Set name
* #param string $name
* #return Theater
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get id
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $work;
/**
* Constructor
*/
public function __construct()
{
$this->work = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add work
*
* #param \Acme\RelationBundle\Entity\Work $work
* #return Theater
*/
public function addWork(\Acme\RelationBundle\Entity\Work $work)
{
$this->work[] = $work;
return $this;
}
/**
* Remove work
* #param \Acme\RelationBundle\Entity\Work $work
*/
public function removeWork(\Acme\RelationBundle\Entity\Work $work)
{
$this->work->removeElement($work);
}
/**
* Get work
* #return \Doctrine\Common\Collections\Collection
*/
public function getWork()
{
return $this->work;
}
}
Then the child entity Work:
class Work
{
// took out some comments to make it shorter
private $name;
private $description;
private $id;
/**
* Set name
* #param string $name
* #return Work
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Set description : And any others setters/getters with the attributes you want
* #param string $description
* #return Work
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get description
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Get id
* #return integer
*/
public function getId()
{
return $this->id;
}
public function __toString()
{
return (string) $this->getName();
}
}
The trick is to use this Collection in Doctrine and then make a two Form Types, the parent and the childs, something like this example below.
TheatherType Formtype includes the Work childs:
$buider->add('rowswork', 'collection', array(
'type' => new WorkChildType(),
'allow_add' => true,
'allow_delete' => true,
)
);
So there is one row with their Work childs that have their own WorkChildType with the attributes from the entity. It's like a form, with an embedded array collection of items, in your case an "RFQ" father form and "RFQitem" childs.
Solved by adding a conditional when adding a new entity to the database, it checks if the entity is not null... apparently there was null entities trying to get saved. Now the controller code looks like this:
...
$ciudades_id = explode(';', $this->getRequest()->getParam('ciudades_id'));
foreach($ciudades_id as $ciudad_id){
$ciudad = $this->_em->find("Application_Model_Ciudades", intval($ciudad_id));
if($ciudad!= null){
$carrera->getCiudad()->add($ciudad);
}
}
$instituciones_id = explode(';', $this->getRequest()->getParam('instituciones_id'));
foreach($instituciones_id as $institucion_id){
$institucion = $this->_em->find("Application_Model_Instituciones", intval($institucion_id));
if($institucion != null){
$carrera->getInstituciones()->add($institucion);
}
}
...
Thanks to the guys that helped at #doctrine IRC channel :)
This is my problem... I got an entity called "Carreras" (carreers) that has some associations, and the new carreers are added to the database with a web form. A carreer for me is a test, which has questions and other atttributes, and the user can select the cities and institutions that apply for that test.
So i'm getting this error when i try to save new data on the entity:
An error occurred
Application error
Exception information:
Message: A new entity was found through the relationship
'Application_Model_Carreras#ciudad' that was not configured
to cascade persist operations for entity: Doctrine\ORM\UnitOfWork#.
Explicitly persist the new entity or configure cascading persist
operations on the relationship. If you cannot find out which entity
causes the problem implement 'Application_Model_Ciudades#__toString()'
to get a clue.
This is the model for "Carreras"
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="carreras")
*/
class Application_Model_Carreras
{
/**
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/** #Column(type="string") */
private $nombre;
/**
* #ManyToMany(targetEntity="Application_Model_PruebasCarrera")
* #JoinTable(name="Carreras_PruebasCarrera",
* joinColumns={#JoinColumn(name="carreras_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="pruebascarrera_id", referencedColumnName="id")}
* )
*/
private $pruebas;
/** #Column(type="integer") */
private $valor;
/** #Column(type="date") */
private $fechainicio;
/** #Column(type="date") */
private $fechafin;
/**
* This association causes error
* #ManyToMany(targetEntity="Application_Model_Ciudades")
* #JoinTable(name="carrera_ciudades",
* joinColumns={#JoinColumn(name="carrera_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="ciudad_id", referencedColumnName="id")}
* )
*/
private $ciudad;
/**
* #ManyToMany(targetEntity="Application_Model_Instituciones")
* #JoinTable(name="carrera_instituciones",
* joinColumns={#JoinColumn(name="carrera_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="institucion_id", referencedColumnName="id")}
* )
*/
private $instituciones;
public function __construct()
{
$this->pruebas = new ArrayCollection();
$this->ciudad = new ArrayCollection();
$this->instituciones = new ArrayCollection();
}
public function setNombre($nombre){
$this->nombre = $nombre;
}
public function setValor($valor){
$this->valor = $valor;
}
public function setFechainicio($fechainicio){
$this->fechainicio = $fechainicio;
}
public function setFechafin($fechafin){
$this->fechafin = $fechafin;
}
public function getCiudad(){
return $this->ciudad;
}
public function getPruebas(){
return $this->pruebas;
}
public function getInstituciones(){
return $this->instituciones;
}
}
Now the action at controller:
/*
* This is an action for adding a new career
*/
public function agregarAction()
{
$formtest = new Admin_Form_AgregarCarrera();
$this->view->formtest = $formtest;
if ($this->getRequest()->isPost() && $this->view->formtest->isValid($this->_getAllParams()))
{
/*
* If the form is okay creating new Carreer model object
* This model has some attributes and three associations (for now)
* you can see them later in detail
*/
$carrera = new Application_Model_Carreras();
$carrera->setNombre($this->getRequest()->getParam("nombre"));
$carrera->setValor($this->getRequest()->getParam("valor"));
$carrera->setFechainicio(new \DateTime($this->getRequest()->getParam("fechainicio")));
$carrera->setFechafin(new \DateTime($this->getRequest()->getParam("fechafin")));
/*
* This is the first association. It's working fine (for now)
*/
$pruebas = $this->getRequest()->getParam("pruebas");
foreach($pruebas as $prueba){
if($prueba != '0'){
$tmp = $this->_em->find("Application_Model_PruebasCarrera", $prueba);
$carrera->getPruebas()->add($tmp);
}
}
/*
* This is the second associations, i'm getting the error with this one
*/
$ciudades_id = explode(';', $this->getRequest()->getParam('ciudades_id'));
foreach($ciudades_id as $ciudad_id){
$ciudad = $this->_em->find("Application_Model_Ciudades", intval($ciudad_id));
$carrera->getCiudad()->add($ciudad);
}
/*
* This is the third one. Nothing to say about this.
*/
$instituciones_id = explode(';', $this->getRequest()->getParam('instituciones_id'));
foreach($instituciones_id as $institucion_id){
$institucion = $this->_em->find("Application_Model_Instituciones", intval($institucion_id));
$carrera->getInstituciones()->add($institucion);
}
$this->_em->persist($carrera);
$this->_em->flush();
//$this->redirector->gotoSimpleAndExit('index','Carrera','admin');
}
}
Well i don't know what else to show... please comment if you can help me :)
--edit
I added cascade={"persist"} in the associations of the model "Carreras" and the error changed:
An error occurred
Application error
Exception information:
Message: Class Doctrine\ORM\UnitOfWork is not a
valid entity or mapped super class.
Now this is "Ciudades" model, it stores the cities available for the test and is associated with the institutions that exist on every city.
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="ciudades")
*/
class Application_Model_Ciudades {
/**
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/** #Column(type="string") */
private $ciudad;
/** #Column(type="string") */
private $departamento;
/** #Column(type="string") */
private $pais;
/**
* #ManyToMany(targetEntity="Application_Model_Instituciones")
* #JoinTable(name="Ciudades_Instituciones",
* joinColumns={#JoinColumn(name="ciudades_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="instituciones_id", referencedColumnName="id")}
* )
*/
private $instituciones;
public function __construct()
{
$this->instituciones = new ArrayCollection();
}
public function getCiudad(){
return $this->ciudad;
}
public function getId(){
return $this->id;
}
public function getInstituciones(){
return $this->instituciones;
}
}
Now this is "Instituciones" Model, it stores the institutions available for the tests.
/**
* #Entity
* #Table(name="instituciones")
*/
class Application_Model_Instituciones {
/**
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/** #Column(type="string") */
private $nombre;
public function getId(){
return $this->id;
}
public function getNombre(){
return $this->nombre;
}
}
Now this is "PruebasCarrera" Model, for me this model entity stores the questions of the tests, and every question can have a partner who supports the question:
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="pruebas_carrera")
*/
class Application_Model_PruebasCarrera extends Application_Model_PruebasBase{
/**
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #ManyToMany(targetEntity="Application_Model_Patrocinadores")
* #JoinTable(name="pruebascarrera_patrocinadores",
* joinColumns={#JoinColumn(name="pruebas_id", referencedColumnName="id", unique="true")},
* inverseJoinColumns={#JoinColumn(name="patrocinadores_id", referencedColumnName="id", unique=false)}
* )
*/
protected $patrocinadores;
/** #Column(type="string") */
private $respuesta;
public function __construct() {
$this->patrocinadores = new ArrayCollection();
}
public function setRespuesta($respuesta){
$this->respuesta = $respuesta;
}
public function getPatrocinadores(){
return $this->patrocinadores;
}
public function getId(){
return $this->id;
}
public function getRespuesta(){
return $this->respuesta;
}
}
Please show code of related entities:
Application_Model_Ciudades
Application_Model_PruebasCarrera
Application_Model_Instituciones
At this moment look https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/working-with-associations.html#transitive-persistence-cascade-operations
At this moment i think you should add cascade={"persist"} to the Application_Model_Ciudades entity.
I have two entities one is Role and other is User , I want to build forms and reports to add and show each role with their users , and to create a user with one Role so its User:Role (One-To-Many), I managed to add role to a user via Doctrine 2 but I cannot show users fro each role below is my code
<?php
/**
* Description of Role
* #Entity
* #Table=(name"Roles")
* #author alaaqashou
*/
class Role {
//put your code here
/**
*
* #var integer $id
* #Column(name="id", type="integer",nullable=false)
* #Id
* #GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #Column(length=100,nullable=false,unique=true)
* #var type
*/
private $name;
/**
* #OneToMany(targetEntity="User" ,mappedBy="Role")
* #var type
*/
private $users;
public function __construct() {
$this->users=new \Doctrine\Common\Collections\ArrayCollection();
}
public function getUsers() {
return $this->users;
}
public function setUsers($user) {
$this->users->add($user);
}
}
/**
* Description of User
*#Entity
* #Tabel(name="Users")
* #author alaaqashou
*/
class User {
//put your code here
/**
*
* #var integer $id
* #Column(name="id", type="integer",nullable=false)
* #Id
* #GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
*
* #Column(length=255,nullable=false,unique=true)
*
*
* #var type
*
*/
private $role;
function __construct() {
$this->created=new \DateTime(date("Y-m-d H:i:s"));
}
public function getRole() {
return $this->role;
}
public function setRole($role) {
$this->role = $role;
}
}
I got the Notice: Undefined index: Role error when I try to do the following
my Service
public function listAllRole()
{
return $this->em->getRepository('sihha\Entity\Role')->findAll();
}
$roles=$this->roleService->listAllRole();
$users=$roles[0]->getUsers();
// I even tried $users=$roles[0]->getUsers()->toArray();
$user=$users[0];
Please Help!!!
I think your problem lies in the annotations. Try replacing mappedBy='Role' width mappedBy='role' (i.e. type "role" in lowercase).
I just tried mappedBy="Table" in one of my entities and it gave me the same result you seem to be having.