Persist a clone - php

In this problem Deep Cloning I thought my issue was due to a deep/shallow copy.
I have vainly tested clone() and unserialize(serialize()) methods.
So I tried to write my own clone function using all setters/getters and then I realized what was really my issue, a persisting one.
The fact is I already succeeded in persisting a clone of my entity, in another context.
The main difference between my two situations is that in one case my original object is already managed by doctrine (this is the case where i'm blocked), and in the second case, my original object is just persisted, I don't have called flush() yet (and it's works fine).
So this is the situation when persist do not persist the many to many relations :
public function duplicateCourseAction(Request $request) {
if ($this->getRequest()->isXmlHttpRequest() == false) {
return new Response("Bad request", 405);
}
$em = $this->getDoctrine()->getManager();
$parameters = $request->request->all();
$course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
$duplicate = clone $course;
$duplicate->setId(null);
$duplicate->setDate(new \DateTime($parameters['date']));
$em->persist($duplicate);
$em->flush();
return new Response("200");
}
And this is the situation whe it's works like a charm
$em->persist($obj);
while ($new_date < $up_to) {
if ($this->isAvailable($holidays, $new_date)) {
$new_course = clone $obj;
$new_course->setDate($new_date);
$new_course->setUuid($uuid);
$new_date = clone $new_date;
$em->persist($new_course);
}
$new_date->modify($modifier);
}
$em->flush();
Why is it working for only one situation ? There are almost identical...
EDIT 1 : Entities Mapping
-Course :
class Course {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=50, unique=true, nullable=true)
*/
protected $name;
/**
* #ORM\JoinColumn(onDelete="CASCADE")
* #ORM\ManyToOne(targetEntity="Ent\HomeBundle\Entity\Campus", inversedBy="courses")
* #Assert\NotBlank
**/
protected $campus;
/**
* #ORM\JoinColumn(onDelete="CASCADE")
* #ORM\ManyToOne(targetEntity="Ent\HomeBundle\Entity\Room", inversedBy="courses")
* #Assert\NotBlank
**/
protected $room;
/**
* #ORM\ManyToMany(targetEntity="Ent\UserBundle\Entity\User", inversedBy="courses", cascade={"persist"})
* #ORM\JoinTable(name="course_teacher",
* joinColumns={#ORM\JoinColumn(name="course_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(name="teacher_id", referencedColumnName="id", onDelete="CASCADE")}
* )
* #Assert\NotBlank
*/
private $teachers;
/**
* #ORM\JoinColumn(onDelete="CASCADE")
* #ORM\ManyToOne(targetEntity="Matter", inversedBy="courses")
* #Assert\NotBlank
**/
protected $matter;
/**
* #ORM\JoinColumn(onDelete="CASCADE")
* #ORM\ManyToOne(targetEntity="\Ent\UserBundle\Entity\Grade", inversedBy="courses")
* #Assert\NotBlank
**/
protected $grade;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank
**/
protected $date;
/**
* #ORM\Column(type="time")
* #Assert\NotBlank
**/
protected $duration;
/**
* #ORM\Column(type="string", length=30, nullable=true)
*/
protected $uuid;
/**
* #ORM\ManyToMany(targetEntity="Ent\TimeBundle\Entity\Course", mappedBy="courses")
* #Exclude
*/
protected $alerts;
public function __toString() {
if (empty($this->getName())) {
$string = $this->getMatter().' - '.$this->getRoom().' - ';
foreach ($this->getTeachers() as $count => $teacher) {
$string = $string . $teacher;
if ($count < count($this->getTeachers()) - 1) {
$string = $string . ', ';
}
}
return $string;
} else {
return $this->getName().' - '.$this->getRoom();
}
}
/**
* Constructor
*/
public function __construct() {
$this->teachers = new ArrayCollection();
$this->alerts = new ArrayCollection();
}
public function __clone() {
// $this->id = null;
// $this->teachers = clone $this->teachers;
}
}
-User (Teacher) :
class User implements UserInterface, \Serializable {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=30)
* #Assert\NotBlank
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=30)
* #Assert\NotBlank
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=70, unique=true)
* #Assert\NotBlank
*/
protected $username;
/**
* #Gedmo\Slug(fields={"username"}, updatable=false)
* #ORM\Column(length=50, unique=true)
*/
protected $slug;
/**
* #ORM\Column(type="string", length=32)
* #Exclude
*/
protected $salt;
/**
* #ORM\Column(type="string", length=40)
* #Exclude
*/
protected $password;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $picture_path;
/**
* #Assert\File(maxSize="10M", mimeTypesMessage="Please upload a valid Image")
*/
protected $picture;
/**
* #ORM\Column(type="string", length=60, unique=true)
* #Exclude
* #Assert\NotBlank
*/
protected $email;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
protected $isActive;
/**
* #ORM\ManyToOne(targetEntity="Group", inversedBy="users")
* #ORM\JoinColumn(name="role_group", referencedColumnName="role", onDelete="CASCADE")
*/
protected $group;
/**
* #ORM\ManyToMany(targetEntity="Ent\HomeBundle\Entity\Campus", inversedBy="users")
* #Exclude
**/
protected $campuses;
/**
* #ORM\OneToMany(targetEntity="\Ent\NewsBundle\Entity\News", mappedBy="user")
* #Exclude
*/
protected $news;
/**
* #ORM\ManyToMany(targetEntity="\Ent\TimeBundle\Entity\Matter", inversedBy="teachers", cascade={"persist"})
* #ORM\JoinTable(name="user_matter",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(name="matter_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
protected $matters;
/**
* #ORM\ManyToMany(targetEntity="Ent\UserBundle\Entity\Grade")
* #Assert\NotBlank
* #Exclude
**/
protected $grades;
/**
* #ORM\ManyToMany(targetEntity="Ent\TimeBundle\Entity\Course", mappedBy="teachers")
* #Exclude
**/
protected $courses;
/**
* #ORM\OneToMany(targetEntity="\Ent\TimeBundle\Entity\Alert", mappedBy="teacher")
* #Exclude
**/
protected $alerts;
protected $temp;
public function __construct() {
$this->isActive = true;
$this->salt = md5(uniqid(null, true));
}
public function __toString() {
return $this->getFullName();
}
}
EDIT 2 : Solution
Thanks to Paul Andrieux this is the function we made to clone my object :
public function course_deep_clone($course) {
$em = $this->getDoctrine()->getManager();
$clone = clone $course;
$clone->setTeachers(array());
$teachers = $course->getTeachers();
foreach ($teachers as $teacher) {
$clone->addTeacher($teacher);
}
return $clone;
}

Thing is that ManyToMany related entities are not cloned, try that:
public function duplicateCourseAction(Request $request) {
if ($this->getRequest()->isXmlHttpRequest() == false) {
return new Response("Bad request", 405);
}
$em = $this->getDoctrine()->getManager();
$parameters = $request->request->all();
$course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
$duplicate = clone $course;
$teachers = $course->getTeachers();
$duplicate->setTeachers($teachers);
$duplicate->setId(null);
$duplicate->setDate(new \DateTime($parameters['date']));
$em->persist($duplicate);
$em->flush();
return new Response("200");
}
This way, you are persisting new relationship and new join table between you two entities
EDIT:
Maybe its a cascading problem, what gives you this ? :
$teachers = $course->getTeachers();
foreach ($teachers as $teacher) {
$teacher->addCourse($duplicate);
$em->persist($teacher);
}

Related

Doctrine rewrites relationship with eager fetching value after findBy

I have a simple entity
/**
* #ORM\Entity(repositoryClass="...\Repository\UserTestRepository")
* #ORM\Table(name="users", uniqueConstraints={
* #ORM\UniqueConstraint(name="U_email", columns={"email"})
* })
* #UniqueEntity("email", message="Email is already used!")
*/
class UserTest
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=180)
* #Assert\NotBlank()
* #Assert\Email()
*/
protected $email;
/**
* #var string
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\NotBlank()
*/
protected $jobTitle;
/**
* #var Company
* #ORM\ManyToOne(targetEntity="...\Entity\Company", fetch="EAGER")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private $company;
public function getId()
{
return $this->id;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function getJobTitle()
{
return $this->jobTitle;
}
public function setJobTitle($jobTitle)
{
$this->jobTitle = $jobTitle;
return $this;
}
public function setCompany(...\Entity\Company $company = null)
{
$this->company = $company;
return $this;
}
public function getCompany()
{
return $this->company;
}
}
and controller
$repo = $this->getDoctrine()->getRepository('..\Entity\UserTest');
$user = $repo->find(519);
dump($user);
$user->setJobTitle('new value');
$user->setCompany(null);
dump($user);
$repo->findBy(['email' => 'test#test.com']);
dump($user);
1-st dump, original
2-nd dump, after changes without flush
3-rd dump, after findBy, jobTitle - with new value, company - original value, changes were lost
Is it normal doctrine behaviour or is it a bug? I use doctrine/orm v2.5.11. Was it fixed in newer versions?
Any help, pls
It's Doctrine normal behaviour when looking for unflushed entity through repository's findBy(). Please refer to https://github.com/doctrine/orm/issues/5092 to get more info.

Doctrine field has value in database but is null when mapped

I am having this strange issue with Doctrine .
When I use find(id) to find an entity, all fields are null except the id. I have double checked the values in database and they are are not null.
The strange thing is when I issue a native mysql query and try to find the entity that doctrine tries to fetch I get non Null value so probably it's a doctrine way of fetching values problem.
Here is my entity :
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
*
*
* #ORM\Entity()
* #ORM\Table(name="hui_address")
*/
class Address
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $client_id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $region_id;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $street;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $city;
/**
* #ORM\Column(name="`state`", type="text", nullable=true)
*/
protected $state;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $zip_code;
/**
* #ORM\Column(type="float", precision=10, scale=6, nullable=true)
*/
protected $latitude;
/**
* #ORM\Column(type="float", precision=10, scale=6, nullable=true)
*/
protected $longitude;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $notes;
/**
* #ORM\Column(name="`status`", type="boolean", nullable=true)
*/
protected $status;
/**
* #ORM\Column(type="smallint", nullable=true)
*/
protected $archive;
/**
* #ORM\Column(type="datetime")
*/
protected $created_at;
/**
* #ORM\OneToMany(targetEntity="Store", mappedBy="address")
* #ORM\JoinColumn(name="id", referencedColumnName="address_id")
*/
protected $Stores;
/**
* #ORM\ManyToOne(targetEntity="Client", inversedBy="Addresses")
* #ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
protected $client;
/**
* #ORM\OneToMany(targetEntity="Client", mappedBy="PPBAddress")
* #ORM\JoinColumn(name="id", referencedColumnName="ppb_address_id")
*/
protected $clientHQ;
/**
* #ORM\ManyToOne(targetEntity="Region", inversedBy="Addresses")
* #ORM\JoinColumn(name="region_id", referencedColumnName="id")
*/
protected $region;
public function __construct()
{
if (!$this->created_at) {
$this->created_at = new \DateTime();
}
$this->Clients = new ArrayCollection();
$this->Stores = new ArrayCollection();
}
public function __toString()
{
return (!$this->street || strlen($this->street) == 0 || !$this->city || !$this->city)
? "Address incomplete"
: sprintf('%s, %s %s %s', $this->street, $this->city, $this->state, $this->zip_code);
}
public function __sleep()
{
return array('id', 'client_id', 'region_id', 'street', 'city', 'state', 'zip_code', 'latitude', 'longitude', 'notes', 'status', 'archive', 'created_at');
}
}
You are missing getters and setters in the entity class.
php bin/console doctrine:generate:entities *your bundle*
will generate them automatically
There was nothing wrong with doctrine. It turns out that the address is fetched from a native query and only the id is selected , that's why I am getting the value for id and null for the rest.
This is how addresses are found :
$query = $this->getManager()->createNativeQuery('SELECT .... ')

Symfony one to many dql query

I am creating symfony web app and have problem with making appropiate dql query for inbox.
This is code of entity causing problems:
class Message
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #OneToOne(targetEntity="User")
* #JoinColumn(name="fromUser", referencedColumnName="id")
*/
protected $fromUser;
/**
* #ORM\Column(type="text")
*/
protected $fromEmail;
/**
* #return mixed
*/
/**
* #OneToOne(targetEntity="User")
* #JoinColumn(name="toUser", referencedColumnName="id")
*/
protected $toUser;
/**
* #ORM\Column(type="text",length=255)
*/
protected $subject;
/**
* #ORM\Column(type="datetimetz")
*/
protected $date;
/**
* #ORM\Column(type="text")
*/
protected $toEmail;
/**
* #ORM\Column(type="text")
*/
protected $content;
/**
* #ORM\Column(type="boolean")
*/
protected $sent;
/**
* #ORM\Column(type="boolean")
*/
protected $spammed;
/**
* #ManyToMany(targetEntity="View")
* #JoinTable(name="messages_views",
* joinColumns={#JoinColumn(name="message_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="view_id", referencedColumnName="id", unique=true)}
* )
*/
protected $view;
class View extends CollectionType
{
public function __construct($user)
{
$this->user = $user;
$this->trashed = false;
$this->deleted = false;
$this->seen = false;
}
/**
* #ORM\Column(type="boolean")
*/
protected $trashed;
/**
* #ORM\Column(type="boolean")
*/
protected $deleted;
/**
* #ORM\Column(type="boolean")
*/
protected $seen;
/**
* #ManyToOne(targetEntity="User")
* #JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
}
$view is class ArrayCollection() and one to many relationship.
And i want to choose field "where $toUser = :me" and which contains $view where $view->user = :me and $view->trashed = false" (in case if there are two $view's (not possible/expected ) choose first found)
Thanks in advance for your time.
Edit:
at the moment i have something like this
$get = $this->getEntityManager()
->createQuery('
SELECT m
FROM MonoAdminBundle:Message m
WHERE m.userTo = :me AND m.sent = true
AND
ORDER BY m.date DESC
')
->setParameter('me', $me->getId())->getArrayResult();
$ret = new \Doctrine\Common\Collections\ArrayCollection();
foreach ($get as $message) {
if ($message->getSpammed() === false) {
foreach ($message->getView() as $view) {
if ($view->getUser() == $me) {
if ($view->getTrashed() === false) {
$ret->add($message);
}
}
}
}
}
But it is not good idea as i want to use paginator.
Try to use a queryBuilder.
$qb = $entityManager->getRepository(Message::class)->createQueryBuilder('m');
$qb->addWhere('m.toUser = :me')
->innerJoin('m.view', v)
->addWhere('v.user = :me')
->addWhere('v.trashed = :isTrashed')
->setParameter('me', $user)
->setParameter('isTrashed', false);
To get DQL:
$qb->getQuery()->getDQL();
Then get results:
$qb->getQuery()->getResults();

Doctrine Inheritance and user types

im new to Doctrine and ORM in general.
I got 4 user types (Admin, Caretaker, Child, Personal).
They all got some of the same columns (id, name, mail, password, created, type & group)
and they got a few columns special to each of them (Caretaker has a child id etc.)
I'm not quite sure how i should map this.
Like should i make my user types extend the User, giving the Child table the user columns, or what would be best practice here?
I assume the the option to use extend would force some more work when doing a login?
User.php
/**
* #MappedSuperclass
* #Entity #Table(name="users")
*/
class User
{
/**
* #Id #GeneratedValue #Column(type="integer")
* #var int
**/
protected $id;
/**
* #Column(type="string")
* #var string
**/
protected $name;
/**
* #Column(type="string")
* #var string
**/
protected $mail;
/**
* #Column(type="string")
* #var string
**/
protected $password;
/**
* #Column(type="datetime")
**/
protected $created;
/**
* #Column(type="datetime")
**/
protected $lastlogin;
/**
* #ManyToOne(targetEntity="Group")
* #JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
/**
* #ManyToOne(targetEntity="Type")
* #JoinColumn(name="type_id", referencedColumnName="id")
*/
protected $type;
public function __construct() {}
public function getId() { return $this->id; }
public function getName() { return $this->name; }
public function getMail() { return $this->mail; }
public function getCreated() { return $this->mail; }
public function getLastLogin() { return $this->lastlogin; }
public function getGroup() { return $this->group; }
public function getType() { return $this->type; }
public function setName($name) { $this->name = $name; }
public function setMail($mail) { $this->mail = $mail; }
public function setCreated() { $this->created = new DateTime("now"); }
public function setLastLogin() { $this->lastlogin = new DateTime("now"); }
public function setGroup($group) { $this->group = $group; }
public function setType($type) { $this->type = $type; }
}
Child.php
// src/Child.php
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity #Table(name="child")
*/
class Child extends User
{
/**
* #Id #OneToOne(targetEntity="User")
* #JoinColumn(name="id", referencedColumnName="id")
**/
protected $id;
/**
* #Column(type="string")
*/
protected $image;
/**
* #ManyToMany(targetEntity="User")
* #JoinTable(name="child_Contacts",
* joinColumns={#JoinColumn(name="child_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="contact_id", referencedColumnName="id")}
* )
*/
protected $currentContacts;
/**
* #OneToMany(targetEntity="Alarm", mappedBy="child")
*/
protected $alarms;
public function __construct()
{
$this->alarms = new ArrayCollection();
}
}
You can easily solve this problem with doctrine and InheritanceType mapping.
Basically, you can do something like this :
/**
* #MappedSuperclass
* #Entity #Table(name="users")
* #InheritanceType("JOINED")
* #DiscriminatorColumn(name="discr", type="string")
* #DiscriminatorMap({"Admin" = "Admin", "Caretaker" = "Caretaker", "Child" = "Child", "Personal" = "Personal"})
*/
class User
{
/**
* #Id #GeneratedValue #Column(type="integer")
* #var int
**/
protected $id;
/**
* #Column(type="string")
* #var string
**/
protected $name;
/**
* #Column(type="string")
* #var string
**/
protected $mail;
/**
* #Column(type="string")
* #var string
**/
protected $password;
/**
* #Column(type="datetime")
**/
protected $created;
/**
* #Column(type="datetime")
**/
protected $lastlogin;
/**
* #ManyToOne(targetEntity="Group")
* #JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
}
And then, in each 4 different classes,
// src/Child.php
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity #Table(name="child")
*/
class Child extends User
{
/**
* #Id #OneToOne(targetEntity="User")
* #JoinColumn(name="id", referencedColumnName="id")
**/
protected $id;
/**
* #Column(type="string")
*/
protected $image;
/**
* #ManyToMany(targetEntity="User")
* #JoinTable(name="child_Contacts",
* joinColumns={#JoinColumn(name="child_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="contact_id", referencedColumnName="id")}
* )
*/
protected $currentContacts;
/**
* #OneToMany(targetEntity="Alarm", mappedBy="child")
*/
protected $alarms;
public function __construct()
{
$this->alarms = new ArrayCollection();
}
}
The doctrine docs is really good for this problem : http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html
And you don't need an extra check at login because doctrine create automatically the right class for you.

Mapping FAIL - The entity-class 'PI\UnidadBundle\Entity\HorasPorUnidad' mapping is invalid

I'm having a problem here and I don't know how to fix it. See I have this two entities:
<?php
namespace PI\ProyectoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* #ORM\Entity
* #ORM\Table(name="proyectos")
* #ORM\Entity(repositoryClass="PI\ProyectoBundle\Entity\Repository\ProyectosRepository")
* #ORM\HasLifecycleCallbacks
*/
class Proyectos {
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=45, unique=true, nullable=false)
*/
protected $nombre;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
protected $estado;
/**
* #ORM\Column(type="string", length=45, nullable=false)
*/
protected $pais;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
* #ORM\JoinColumn(name="cliente", referencedColumnName="id")
*/
protected $clientes;
/**
* #ORM\ManyToMany(targetEntity="PI\CentroBundle\Entity\Centros", inversedBy="proyectos", cascade={"persist"})
* #ORM\JoinTable(name="proyectos_has_centros",
* joinColumns={#ORM\JoinColumn(name="proyectos_id", referencedColumnName="id"),
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="cliente")},
* inverseJoinColumns={#ORM\JoinColumn(name="centros_id", referencedColumnName="id")}
* )
*/
protected $centros;
/**
* #ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User", cascade={"persist"})
* #ORM\JoinTable(name="proyectos_has_system_user",
* joinColumns={#ORM\JoinColumn(name="proyectos_id", referencedColumnName="id"),
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="cliente")},
* inverseJoinColumns={#ORM\JoinColumn(name="system_user_id", referencedColumnName="id")}
* )
*/
protected $ingenieros;
public function __construct() {
$this->centros = new \Doctrine\Common\Collections\ArrayCollection();
$this->ingenieros = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function setNombre($nombre) {
$this->nombre = $nombre;
}
public function getNombre() {
return $this->nombre;
}
public function setEstado($estado) {
$this->estado = $estado;
}
public function getEstado() {
return $this->estado;
}
public function setPais($pais) {
$this->pais = $pais;
}
public function getPais() {
return $this->pais;
}
public function setClientes(\PI\ClienteBundle\Entity\Clientes $clientes) {
$this->clientes = $clientes;
}
public function getClientes() {
return $this->clientes;
}
public function setCentros(\PI\CentroBundle\Entity\Centros $centros) {
$this->centros[] = $centros;
}
public function getCentros() {
return $this->centros;
}
public function setIngenieros(\BIT\UserBundle\Entity\User $ingenieros) {
$this->ingenieros[] = $ingenieros;
}
public function getIngenieros() {
return $this->ingenieros;
}
/**
* #ORM\PrePersist
*/
public function prePersist(LifecycleEventArgs $eventArgs) {
$em = $eventArgs->getEntityManager();
$q = $em->createQuery('SELECT MAX(p.id) FROM PIProyectoBundle:Proyectos p');
$id = $q->getSingleResult(\Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);
$this->id = $id + 1;
}
}
And this other:
<?php
namespace PI\UnidadBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="horas_por_proyectos")
*/
class HorasPorUnidad {
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User", cascade={"all"})
* #ORM\JoinColumn(name="fos_user_user_id", referencedColumnName="id")
*/
protected $fos_user_user_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\UnidadBundle\Entity\Unidades", cascade={"all"})
* #ORM\JoinColumn(name="fos_user_user_id", referencedColumnName="id")
*/
protected $unidades_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\CentroBundle\Entity\Centros", cascade={"all"})
* #ORM\JoinColumn(name="centros_id", referencedColumnName="id")
*/
protected $centros_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ProyectoBundle\Entity\Proyectos", cascade={"all"})
* #ORM\JoinColumn(name="proyectos_id", referencedColumnName="id")
*/
protected $proyectos_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="id")
*/
protected $proyectos_cliente;
/**
* #ORM\Column(type="date")
*/
protected $fecha;
/**
* #ORM\Column(type="integer")
*/
protected $horas;
public function setUserId(\Application\Sonata\UserBundle\Entity\User $user) {
$this->fos_user_user_id = $user;
}
public function getUserId() {
return $this->fos_user_user_id;
}
public function setUnidadesId(\PI\UnidadBundle\Entity\Unidades $unidad) {
$this->unidades_id = $unidad;
}
public function getUnidadesId() {
return $this->unidades_id;
}
public function setCentrosId(\PI\CentroBundle\Entity\Centros $centro) {
$this->centros_id = $centro;
}
public function getCentrosId() {
return $this->centros_id;
}
public function setHoras($cantidad_horas) {
$this->horas = $cantidad_horas;
}
public function getHoras() {
return $this->horas;
}
public function setFecha($fecha) {
$this->fecha = $fecha;
}
public function getFecha() {
return $this->fecha;
}
}
But when I run the task php app/console doctrine:schema:validate I get this errors:
[Mapping] FAIL - The entity-class 'PI\UnidadBundle\Entity\HorasPorUnidad' mapping is invalid:
Cannot map association 'PI\UnidadBundle\Entity\HorasPorUnidad#proyectos_id as identifier, because the target entity 'PI\ProyectoBundle\Entity\Proyectos' also maps an association as identifier.
The join columns of the association 'proyectos_id' have to match to ALL identifier columns of the target entity 'PI\UnidadBundle\Entity\HorasPorUnidad', however 'id, cliente' are missing.
And I don't know how to fix them, so any help from experts? What I need to fix here?
You foget the mappedBy and inversedBy attributes in the ManyToOne assocciation and also check the other side of your assocciations:
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes",inversedBy="?" cascade={"all"})
* #ORM\JoinColumn(name="cliente", referencedColumnName="id")
*/
protected $clientes;

Categories