kamilo.cervantes
kamilo.cervantes

Reputation: 15

Doctrine 2: inserting data into an entity with associations

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;
    }

}

Upvotes: 1

Views: 4918

Answers (1)

Artur Michalak
Artur Michalak

Reputation: 459

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.

Upvotes: 1

Related Questions