Error with mass flush objects doctrine - php

This causes an error:
$em = $this->getDoctrine()->getManager();
$courses = $em->getRepository(Course::class)->findBy(['id' => $ids]);
foreach ($courses as $course) {
$data = $form->getData();
$course->setProperties($data);
$em->persist($course);
}
$em->flush();
The followin error is thown:
Type error:
Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::
__construct() must be of the type array, null given, called in:
/var/www/bib/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1064
But when I insert $em->flush(); In a cycle - everything works.
What wrong?
Course entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use CoreBundle\Entity\GuidTrait;
use CoreBundle\Entity\Typo3Trait;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
use CoreBundle\Entity\LoggableTrait;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\CourseRepository")
* #ORM\Table(name="courses")
* #ORM\HasLifecycleCallbacks()
*/
class Course
{
use GuidTrait, Typo3Trait, Timestampable, LoggableTrait;
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
/**
* #ORM\Column(type="string", length=150, nullable=true)
*/
protected $title;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string")
*/
protected $code;
/**
* #Assert\NotBlank()
* #ORM\Column(name="`order`", type="integer")
*/
protected $order;
/**
* #Assert\NotBlank()
* #ORM\Column(type="smallint")
*/
protected $status;
/**
* #Assert\NotBlank()
* #Assert\DateTime()
* #ORM\Column(type="datetime", nullable=false)
*/
protected $date;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $enrolmentDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $durationDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $timetable;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactName;
/**
* #Assert\NotBlank()
* #Assert\Email
* #ORM\Column(type="string", nullable=false)
*/
protected $contactEmail;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactPhone;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $contactFax;
/**
* #Assert\NotBlank()
* #Assert\Type(type="float")
* #Assert\GreaterThanOrEqual(0)
*
* #ORM\Column(type="decimal", precision=8, scale=2, nullable=false)
*/
protected $price;
/**
* #Assert\NotBlank()
* #Assert\GreaterThanOrEqual(0)
* #Assert\Type(type="integer")
*
* #ORM\Column(type="integer", nullable=false)
*/
protected $availability;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $courseNotes;
/**
* #ORM\ManyToOne(targetEntity="Centre", inversedBy="courses")
* #ORM\JoinColumn(name="centre_id", referencedColumnName="uid")
*/
protected $centre;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Qualification", inversedBy="courses")
* #ORM\JoinColumn(name="qualification_id", referencedColumnName="uid",onDelete="CASCADE")
*/
protected $qualification;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Venue", inversedBy="courses")
* #ORM\JoinColumn(name="venue_id", referencedColumnName="uid")
*/
protected $venue;
/**
* #ORM\OneToMany(targetEntity="Booking", mappedBy="course", cascade={"remove"})
*/
protected $bookings;
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $reference;
public function __construct()
{
$this->status = self::STATUS_ACTIVE;
$this->code = 'CODE';
$this->order = 1;
}
/**
* #ORM\PreFlush
*/
public function updateReference()
{
$q = $this->getQualification()->getCode();
$c = $this->getCentre()->getCode();
$v = $this->getVenue()->getCode();
$d = $this->getDate()->format('d/m/Y');
$this->setReference("$q - $c - $v - $d");
}
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param $title
* #return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* #return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* #param $code
* #return $this
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #return mixed
*/
public function getOrder()
{
return $this->order;
}
/**
* #param $order
* #return $this
*/
public function setOrder($order)
{
$this->order = $order;
return $this;
}
/**
* #return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* #param $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param $date
* #return $this
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* #return mixed
*/
public function getEnrolmentDetails()
{
return $this->enrolmentDetails;
}
/**
* #param $enrolmentDetails
* #return $this
*/
public function setEnrolmentDetails($enrolmentDetails)
{
$this->enrolmentDetails = $enrolmentDetails;
return $this;
}
/**
* #return mixed
*/
public function getDurationDetails()
{
return $this->durationDetails;
}
/**
* #param $durationDetails
* #return $this
*/
public function setDurationDetails($durationDetails)
{
$this->durationDetails = $durationDetails;
return $this;
}
/**
* #return mixed
*/
public function getTimetable()
{
return $this->timetable;
}
/**
* #param $timetable
* #return $this
*/
public function setTimetable($timetable)
{
$this->timetable = $timetable;
return $this;
}
/**
* #return mixed
*/
public function getContactName()
{
return $this->contactName;
}
/**
* #param $contactName
* #return $this
*/
public function setContactName($contactName)
{
$this->contactName = $contactName;
return $this;
}
/**
* #return mixed
*/
public function getContactEmail()
{
return $this->contactEmail;
}
/**
* #param $contactEmail
* #return $this
*/
public function setContactEmail($contactEmail)
{
$this->contactEmail = $contactEmail;
return $this;
}
/**
* #return mixed
*/
public function getContactPhone()
{
return $this->contactPhone;
}
/**
* #param $contactPhone
* #return $this
*/
public function setContactPhone($contactPhone)
{
$this->contactPhone = $contactPhone;
return $this;
}
/**
* #return mixed
*/
public function getContactFax()
{
return $this->contactFax;
}
/**
* #param $contactFax
* #return $this
*/
public function setContactFax($contactFax)
{
$this->contactFax = $contactFax;
return $this;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param $price
* #return $this
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* #return mixed
*/
public function getAvailability()
{
return $this->availability;
}
/**
* #param $availability
* #return $this
*/
public function setAvailability($availability)
{
$this->availability = $availability;
return $this;
}
/**
* #return mixed
*/
public function getCourseNotes()
{
return $this->courseNotes;
}
/**
* #param $courseNotes
* #return $this
*/
public function setCourseNotes($courseNotes)
{
$this->courseNotes = $courseNotes;
return $this;
}
/**
* #return mixed
*/
public function getCentre()
{
return $this->centre;
}
/**
* #param $centre
* #return $this
*/
public function setCentre($centre)
{
$this->centre = $centre;
return $this;
}
/**
* #return mixed
*/
public function getQualification()
{
return $this->qualification;
}
/**
* #param $qualification
* #return $this
*/
public function setQualification($qualification)
{
$this->qualification = $qualification;
return $this;
}
/**
* #return mixed
*/
public function getVenue()
{
return $this->venue;
}
/**
* #param $venue
* #return $this
*/
public function setVenue($venue)
{
$this->venue = $venue;
return $this;
}
/**
* #return mixed
*/
public function getReference()
{
return $this->reference;
}
/**
* #param $reference
* #return $this
*/
public function setReference($reference)
{
$this->reference = $reference;
return $this;
}
/**
* #return mixed
*/
public function getBookings()
{
return $this->bookings;
}
/**
* #param mixed $bookings
*/
public function setBookings($bookings)
{
$this->bookings = $bookings;
}
public function getVat( $amount = 0 )
{
if (empty($amount)) {
return round( $this->price * $this->centre->getVat()->getRate()/100, 2 );
} else {
return round( $amount * $this->centre->getVat()->getRate()/100, 2 );
}
}
public function setProperties(Course $course)
{
foreach ($this as $key=>$value) {
if ($course->$key) {
$this->$key = $course->$key;
}
}
}
}
There is nothing supernatural in this entity.
Does anyone have an answer to the question I asked?

There are many issues in Symfony and Doctrine when you execute the flush() method. For example, calling flush() inside a Doctrine listener is not a supported Doctrine usage. it means you are trying to nest several flushes inside each other, which can indeed break the unit of work.
There is a really complete examplample in this StackOverflow Answer, but I think it maybe not be enaugh to understand your problem, so if you want you can check all the posible scenarios where flush should fail here:
https://github.com/doctrine/doctrine2/issues/4004

Related

Why my symfony entity is not managed?

I have a Portfolio entity which is working well to create or update but I can't delete it. Symfony throws this error:
Entity matthieu-appriou is not managed. An entity is managed if its
fetched from the database or registered as new through
EntityManager#persist
Here is my entity:
<?php
namespace CreasensoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SensoBundle\Entity\Talent;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use JMS\Serializer\Annotation\MaxDepth;
use JMS\Serializer\Annotation\Exclude;
/**
* Portfolio
*
* #ORM\Entity
* #ORM\Table(name="portfolio")
* #ORM\Entity(repositoryClass="CreasensoBundle\Repository\PortfolioRepository")
*/
class Portfolio
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean", nullable=true)
*/
private $visible;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Talent", cascade={"persist", "remove"}, inversedBy="portfolio")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $talent;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Image", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $image;
/**
* #var string
*
* #ORM\Column(name="folio_label", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $folioLabel;
/**
* #var string
*
* #ORM\Column(name="main_customers", type="string", length=400, nullable=true)
*/
private $mainCustomers;
/**
* #var string
*
* #ORM\Column(name="main_agencies", type="string", length=400, nullable=true)
*/
private $mainAgencies;
/**
* #var string
*
* #ORM\Column(name="publications", type="string", length=700, nullable=true)
*/
private $publications;
/**
* #var string
*
* #ORM\Column(name="description_title", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $descriptionTitle;
/**
* #var string
*
* #ORM\Column(name="description_content", type="text", nullable=true)
* #Gedmo\Translatable
*/
private $descriptionText;
/**
* #MaxDepth(2)
* #ORM\ManyToMany(targetEntity="SensoBundle\Entity\Expertise", cascade={"persist"})
*/
private $expertises;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var \DateTime $updated
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $mostRecentProjectDate;
/**
* #var \DateTime $featuredTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $featuredTime;
/**
* #var \DateTime $submissionTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $submissionTime;
/**
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->setVisible(false);
$this->expertises = new ArrayCollection();
}
public function __toString() {
return $this->getSlug();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
public function getSlug()
{
return $this->getTalent()->getSlug();
}
/**
* Set visible
*
* #param boolean $visible
*
* #return Portfolio
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getTalent()
{
return $this->talent;
}
/**
* #param mixed $talent
*/
public function setTalent($talent)
{
$this->talent = $talent;
$talent->setPortfolio($this);
}
/**
* #return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* #param mixed $image
*/
public function setImage($image)
{
if ($image) {
$image->setParentType('portfolio');
}
$this->image = $image;
}
/**
* #return string
*/
public function getMainCustomers()
{
return $this->mainCustomers;
}
/**
* #param string $mainCustomers
*/
public function setMainCustomers($mainCustomers)
{
$this->mainCustomers = $mainCustomers;
}
/**
* #return string
*/
public function getMainAgencies()
{
return $this->mainAgencies;
}
/**
* #param string $mainAgencies
*/
public function setMainAgencies($mainAgencies)
{
$this->mainAgencies = $mainAgencies;
}
/**
* #return string
*/
public function getDescriptionTitle()
{
return $this->descriptionTitle;
}
/**
* #param string $descriptionTitle
*/
public function setDescriptionTitle($descriptionTitle)
{
$this->descriptionTitle = $descriptionTitle;
}
/**
* #return string
*/
public function getDescriptionText()
{
return $this->descriptionText;
}
/**
* #param string $descriptionText
*/
public function setDescriptionText($descriptionText)
{
$this->descriptionText = $descriptionText;
}
public function addExpertise($expertise)
{
$this->expertises[] = $expertise;
return $this;
}
public function removeExpertise($expertise)
{
$this->expertises->removeElement($expertise);
}
public function getExpertises()
{
return $this->expertises;
}
public function setExpertises($expertises)
{
$this->expertises = $expertises;
}
/**
* #return mixed
*/
public function getCreated()
{
return $this->created;
}
/**
* #param mixed $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #param \DateTime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* #return \DateTime
*/
public function getFeaturedTime()
{
return $this->featuredTime;
}
/**
* #param \DateTime $featuredTime
*/
public function setFeaturedTime($featuredTime)
{
$this->featuredTime = $featuredTime;
}
/**
* #return string
*/
public function getPublications()
{
return $this->publications;
}
/**
* #param string $publications
*/
public function setPublications($publications)
{
$this->publications = $publications;
}
/**
* #return mixed
*/
public function getSubmissionTime()
{
return $this->submissionTime;
}
/**
* #param mixed $submissionTime
*/
public function setSubmissionTime($submissionTime)
{
$this->submissionTime = $submissionTime;
}
/**
* #return string
*/
public function getFolioLabel()
{
return $this->folioLabel;
}
/**
* #param string $folioLabel
*/
public function setFolioLabel($folioLabel)
{
$this->folioLabel = $folioLabel;
}
public function getType()
{
return 'portfolio';
}
/**
* #return \DateTime
*/
public function getMostRecentProjectDate()
{
return $this->mostRecentProjectDate;
}
/**
* #param \DateTime $mostRecentProjectDate
*/
public function setMostRecentProjectDate($mostRecentProjectDate)
{
$this->mostRecentProjectDate = $mostRecentProjectDate;
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
}
And here is the code sample I use to reproduce this error:
<?php
// namespace and use ...
/**
* Tool controller.
*
* #Route("/admin/test")
*/
class TestController extends Controller
{
/**
*
* #Route("/testTwo", name="testTwo")
* #Method({"GET", "POST"})
*/
public function indexTwoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$pr = $this->get('creasenso.portfolio_repo');
$p = $pr->find(32);
$em->remove($p);
$em->flush();
return new Response("<html><head></head><body><hr />Done</body></html>");
}
}
Here is the repository linked to this entity:
<?php
namespace CreasensoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* PortfolioRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PortfolioRepository extends EntityRepository
{
protected $qb;
public function init()
{
$this->qb = $this->createQueryBuilder('p');
}
public function isVisible()
{
$this->qb
->andWhere('p.visible = :visible')
->setParameter(':visible', 1);
}
public function getAllPublicPortfolioCount()
{
$this->init();
$this->isVisible();
$this->qb->select('COUNT(p)');
return $this->qb->getQuery()->getSingleScalarResult();
}
public function getQueryBuilder()
{
return $this->qb;
}
}
Do you have any clue about this behavior? Thank you very much.
You are getting your repository directly from the service container when you should be getting it from your EntityManager through getRepository().
You are not loading your entity from the entityManager that you flush so it is not managed

Symfony ArrayCollection vs PersistentCollection

As I understood when you query database by repository you get PersistentCollection and when your working with your entities you get ArrayCollection.
so consider I have one to many self referencing relation for my user entity.
and in my user entity I have a setChildren method which get ArrayCollection of users as argument .
<?php
namespace UserBundle\Entity;
use Abstracts\Entity\BaseModel;
use CertificateBundle\Entity\Certificate;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use EducationBundle\Entity\Education;
use LanguageBundle\Entity\Language;
use PostBundle\Entity\Post;
use ProfileBundle\Entity\Company;
use RoleBundle\Entity\Role;
use SkillBundle\Entity\Skill;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="UserBundle\Repository\Entity\UserRepository")
* #UniqueEntity("email")
* #UniqueEntity("username")
*/
class User implements UserInterface
{
use BaseModel;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="type", type="string", columnDefinition="ENUM('merchant', 'company', 'customer') ")
*/
private $type;
/**
* #ORM\Column(type="string", unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
*/
private $avatar = null;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
*/
private $cover = null;
/**
* #ORM\OneToMany(targetEntity="PostBundle\Entity\Post", mappedBy="user", orphanRemoval=true, cascade={"persist", "remove"})
*/
private $posts;
/**
* #ORM\OneToMany(targetEntity="EducationBundle\Entity\Education" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $educations;
/**
* #ORM\OneToMany(targetEntity="SkillBundle\Entity\SkillUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $skills;
/**
* #ORM\OneToMany(targetEntity="LanguageBundle\Entity\LanguageUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $languages;
/**
* #ORM\OneToMany(targetEntity="ResumeBundle\Entity\Resume" , mappedBy="user" , cascade={"all"})
*/
protected $resumes;
/**
* #ORM\OneToMany(targetEntity="CertificateBundle\Entity\CertificateUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $certificates;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Company", mappedBy="user")
*/
protected $company;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Customer", mappedBy="user")
*/
protected $customer;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Merchant", mappedBy="user")
*/
protected $merchant;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(min=4)
* #ORM\Column(name="password", type="string", length=255)
*
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity="RoleBundle\Entity\Role", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(name="user_role", joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")}, inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")})
*/
private $roles;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
/**
* #ORM\OneToMany(targetEntity="UserBundle\Entity\User", mappedBy="parent", orphanRemoval=true, cascade={"persist", "remove"})
*
*/
protected $children;
/**
* #var array
*/
public static $fields = [ 'email', 'username', 'id', 'avatar', 'cover', 'type'];
/**
* User Entity constructor.
*/
public function __construct(/*EncoderFactoryInterface $encoderFactory*/)
{
//$this->encoderFactory = $encoderFactory;
$this->posts = new ArrayCollection();
$this->skills = new ArrayCollection();
$this->languages = new ArrayCollection();
$this->certificates = new ArrayCollection();
$this->educations = new ArrayCollection();
$this->children = new ArrayCollection();
dump($this->children);
die();
}
/**
* #param User $user
* #return $this
*/
public function setParent(User $user)
{
$this->parent = $user;
return $this;
}
/**
* #return $this
*/
public function removeParent()
{
$this->parent = null;
return $this;
}
/**
* #param User $user
* #return $this
*/
public function addChild(User $user)
{
if(!$this->children->contains($user)){
$this->children->add($user);
}
return $this;
}
/**
* #param User $user
* #return bool
*/
public function hasChild(User $user)
{
return $this->children->contains($user);
}
/**
* #param User $user
* #return bool
*/
public function isChildOf(User $user)
{
return $user->getChildren()->contains($this);
}
/**
* #return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* #param User $user
* #return $this
*/
public function removeChild(User $user)
{
if($this->children->contains($user)){
$this->children->removeElement($user);
}
return $this;
}
/**
* #param ArrayCollection $users
* #return $this
*/
public function setChildren(ArrayCollection $users)
{
$this->children = $users;
return $this;
}
/**
* #return $this
*/
public function removeChildren()
{
$this->children->clear();
return $this;
}
/**
* #param ArrayCollection $certificates
* #return $this
*/
public function setCertificates(ArrayCollection $certificates)
{
$this->certificates = $certificates;
return $this;
}
/**
* #param Certificate $certificate
* #return $this
*/
public function addCertificate(Certificate $certificate)
{
if(!$this->certificates->contains($certificate))
$this->certificates->add($certificate);
return $this;
}
/**
* #param Certificate $certificate
* #return $this
*/
public function removeCertificate(Certificate $certificate)
{
if($this->certificates->contains($certificate))
$this->certificates->removeElement($certificate);
return $this;
}
/**
* #return $this
*/
public function removeCertificates()
{
$this->certificates->clear();
return $this;
}
/**
* #param ArrayCollection $skills
* #return $this
*/
public function setSkills(ArrayCollection $skills)
{
$this->skills = $skills;
return $this;
}
/**
* #param Skill $skill
* #return $this
*/
public function addSkill(Skill $skill)
{
if(!$this->skills->contains($skill))
$this->skills->add($skill);
return $this;
}
/**
* #param Skill $skill
* #return $this
*/
public function removeSkill(Skill $skill)
{
if($this->skills->contains($skill))
$this->skills->removeElement($skill);
return $this;
}
/**
* #return $this
*/
public function removeSkills()
{
$this->skills->clear();
return $this;
}
/**
* #param ArrayCollection $languages
* #return $this
*/
public function setLanguages(ArrayCollection $languages)
{
$this->languages = $languages;
return $this;
}
/**
* #param Language $language
* #return $this
*/
public function addLanguage(Language $language)
{
if(!$this->languages->contains($language))
$this->languages->add($language);
return $this;
}
/**
* #param Language $language
* #return $this
*/
public function removeLanguage(Language $language)
{
if($this->languages->contains($language))
$this->languages->removeElement($language);
return $this;
}
/**
* #return $this
*/
public function removeLanguages()
{
$this->languages->clear();
return $this;
}
/**
* #param ArrayCollection $posts
* #return $this
*/
public function setPosts(ArrayCollection $posts)
{
$this->posts = $posts;
return $this;
}
/**
* #param Post $post
* #return $this
*/
public function addPost(Post $post)
{
$this->posts->add($post);
return $this;
}
/**
* #param Post $post
* #return $this
*/
public function removePost(Post $post)
{
$this->posts->removeElement($post);
return $this;
}
/**
* #return $this
*/
public function removePosts()
{
$this->posts->clear();
return $this;
}
/**
* #param ArrayCollection $educations
* #return $this
*/
public function setEducations(ArrayCollection $educations)
{
$this->educations = $educations;
return $this;
}
/**
* #param Education $education
* #return $this
*/
public function addEducation(Education $education)
{
$this->educations->add($education);
return $this;
}
/**
* #param Education $education
* #return $this
*/
public function removeEducation(Education $education)
{
$this->educations->removeElement($education);
return $this;
}
/**
* #return $this
*/
public function removeEducations()
{
$this->educations->clear();
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #param integer $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
* #return $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param $username
* #return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* #return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* #return array
*/
public function getRoles()
{
return ['ROLE_USER', 'IS_AUTHENTICATED_ANONYMOUSLY'];
}
/**
* #param $password
* #return $this
*/
public function setPassword($password)
{
//$password =$this->encoderFactory->getEncoder($this)->encodePassword($password, $this->getSalt());
$this->password = $password;
return $this;
}
/**
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
*
*/
public function getSalt()
{
return md5(sha1('somesalt'));
}
/**
*
*/
public function eraseCredentials()
{
}
/**
* #param $cover
* #return $this
*/
public function setCover($cover)
{
$this->cover = $cover;
return $this;
}
/**
* #return string
*/
public function getCover()
{
return $this->cover;
}
/**
* #param $avatar
* #return $this
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* #param Role $roles
*/
public function addRoles(Role $roles)
{
$this->roles[] = $roles;
}
/**
* #return mixed
*/
public function getRoles2()
{
return $this->roles;
}
/**
* #return array
*/
public function getRolesAsArray()
{
$rolesArray = [];
foreach ($this->getRoles2() as $role) {
$rolesArray[] = $role->getName();
}
return $rolesArray;
}
/**
* #return Company
*/
public function getCompany()
{
return $this->company;
}
/**
* #param Company $company
* #return $this
*/
public function setCompany(Company $company)
{
$this->company = $company;
return $this;
}
}
and this is what I want to do
$new_owner = $this->userRepository->findOneById($user_id, false);
$children = $old_owner->getChildren();
$old_owner->removeChildren();
$new_owner->setChildren($children);
and I get error which says :
Argument 1 passed to
Proxies__CG__\UserBundle\Entity\User::setChildren() must be an
instance of Doctrine\Common\Collections\ArrayCollection, instance of
Doctrine\ORM\PersistentCollection given
should I change my type hint in setChildren method to PersistentCollection ??
or I need to totally change my approach?
Short answer:
/**
* #param Doctrine\Common\Collections\Collection $users
* #return $this
*/
public function setChildren(Doctrine\Common\Collections\Collection $users)
{
$this->children = $users;
return $this;
}
Explanation:
If you look deep into Doctrine Classes you will see the following structure:
Array collection is class that implements interface Collection:
class ArrayCollection implements Collection, Selectable
PersistentCollection is class that extentds AbstractLazyCollection:
final class PersistentCollection extends AbstractLazyCollection implements Selectable
but AbstractLazyCollection implements Collection:
abstract class AbstractLazyCollection implements Collection
So:
Collection is interface, that you should use in method setChildren().
This is because of doctrine use lazy loading - mechanism that allow to load not all properties, but only these, that are needed.
Similar question:
Doctrine manyToMany return PersistentCollection instead of ArrayCollection
In your typing add Collection $children
use Doctrine\Common\Collections\Collection;
...
private ?Collection $children;
symfony: 5.3

Symfony2 After form submit entity not extended on base entity

In editAction method of controller I tried to edit existed entities in class table inheritance.
But after form submit I get error:
Neither the property "id" nor one of the methods
"addId()"/"removeId()", "setId()", "id()", "__set()" or "__call()"
exist and have public access in class "AdBundle\Entity\AdFlat".
Why AdFlat entity not extended of AdBase entity?
Base entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdBase
*
* #ORM\Table(name="ad_base")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdBaseRepository")
* #ORM\HasLifecycleCallbacks()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
"flat" = "AdFlat"
* })
*/
abstract class AdBase
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdCategory")
*/
private $category;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Field Location should not be blank")
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank(message="Not specified Title")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Assert\NotBlank(message="Not specified Description")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="ad")
*/
private $photos;
/**
* #ORM\Column(type="float")
* #Assert\NotBlank()
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdPriceType")
*/
private $priceType;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean")
*/
private $visible = false;
/**
* #ORM\Column(type="boolean")
*/
private $active = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set author
*
* #param string $author
*
* #return AdBase
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Set title
*
* #param string $title
*
* #return AdBase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return AdBase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set photos
*
* #param string $photos
*
* #return AdBase
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
/**
* Get photos
*
* #return string
*/
public function getPhotos()
{
return $this->photos;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getPriceType()
{
return $this->priceType;
}
/**
* #param mixed $priceType
*/
public function setPriceType($priceType)
{
$this->priceType = $priceType;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return AdBase
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param string $updatedAt
*
* #return AdBase
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set visible
*
* #param boolean $visible
*
* #return AdBase
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #ORM\PrePersist()
*/
public function prePersist()
{
$this->author = 'voodoo';
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->location = 'Donetsk';
}
/**
* #ORM\PreUpdate()
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
Extended entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdFlat
*
* #ORM\Table(name="ad_flat")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdFlatRepository")
*/
class AdFlat extends AdBase
{
/**
* #var integer
*
* #ORM\Column(type="integer")
* #Assert\NotBlank(message="ad_flat.rooms.not_blank")
*/
private $rooms;
/**
* #var float
*
* #ORM\Column(name="square", type="float", nullable=true)
*/
private $square;
/**
* #var float
*
* #ORM\Column(name="liveSquare", type="float", nullable=true)
*/
private $liveSquare;
/**
* #var float
*
* #ORM\Column(type="float", nullable=true)
*/
private $kitchenSquare;
/**
* #var int
*
* #ORM\Column(name="floor", type="integer")
*/
private $floor;
/**
* #var int
*
* #ORM\Column(name="floors", type="integer")
*/
private $floors;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWallType")
*/
private $wallType;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWCType")
*/
private $wcType;
/**
* #return mixed
*/
public function getRooms()
{
return $this->rooms;
}
/**
* #param mixed $rooms
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
}
/**
* Set square
*
* #param float $square
*
* #return AdFlat
*/
public function setSquare($square)
{
$this->square = $square;
return $this;
}
/**
* Get square
*
* #return float
*/
public function getSquare()
{
return $this->square;
}
/**
* Set liveSquare
*
* #param float $liveSquare
*
* #return AdFlat
*/
public function setLiveSquare($liveSquare)
{
$this->liveSquare = $liveSquare;
return $this;
}
/**
* Get liveSquare
*
* #return float
*/
public function getLiveSquare()
{
return $this->liveSquare;
}
/**
* #return float
*/
public function getKitchenSquare()
{
return $this->kitchenSquare;
}
/**
* #param float $kitchenSquare
*/
public function setKitchenSquare($kitchenSquare)
{
$this->kitchenSquare = $kitchenSquare;
}
/**
* Set floor
*
* #param integer $floor
*
* #return AdFlat
*/
public function setFloor($floor)
{
$this->floor = $floor;
return $this;
}
/**
* Get floor
*
* #return int
*/
public function getFloor()
{
return $this->floor;
}
/**
* Set floors
*
* #param integer $floors
*
* #return AdFlat
*/
public function setFloors($floors)
{
$this->floors = $floors;
return $this;
}
/**
* Get floors
*
* #return int
*/
public function getFloors()
{
return $this->floors;
}
/**
* Set wallType
*
* #param string $wallType
*
* #return AdFlat
*/
public function setWallType($wallType)
{
$this->wallType = $wallType;
return $this;
}
/**
* Get wallType
*
* #return string
*/
public function getWallType()
{
return $this->wallType;
}
/**
* Set wcType
*
* #param string $wcType
*
* #return AdFlat
*/
public function setWcType($wcType)
{
$this->wcType = $wcType;
return $this;
}
/**
* Get wcType
*
* #return string
*/
public function getWcType()
{
return $this->wcType;
}
}
In controller:
public function editAction(Request $request)
{
$adId = $request->get('id');
if (!$adId) {
return $this->renderError('Unknown Ad');
}
$adEntity = $this->getDoctrine()->getRepository('AdBundle:AdBase')->find($adId);
if (null === $adEntity) {
return $this->renderError('Unknown Ad');
}
$reflection = new \ReflectionClass($adEntity);
$adForm = $this->getForm($reflection->getShortName());
$form = $this->createForm($adForm, $adEntity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($adEntity);
$em->flush();
return $this->redirectToRoute('ad_bundle_ad_view', array(
'id' => $adEntity->getId()
));
}
return $this->render('AdBundle:Ad:edit-ad-flat.html.twig', array(
'form' => $form->createView()
));
}
private function renderError($message = '')
{
return $this->render('::error.html.twig', array(
'error' => $message
));
}
private function getEntity($className)
{
$entityName = 'AdBundle\Entity\\' . $className;
return new $entityName();
}
private function getForm($className)
{
$formName = 'AdBundle\Form\Type\\' . $className . 'Type';
return new $formName();
}
The error message simply states that you are missing a way to set the entity's $id property. It doesn't tell you anything about the class not extending the base class. However, your base class only defines a getter method for the $id property but no setter method.
Doctrine Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly you need to work with the MappedSuperClass here is an example

How to add properly one-to-many relationship in Doctrine 2?

I have 2 files(tables) in my Entity, and want to join Like table to Comment table.I used one to many so can connect Comment.id to Like.comment_id and can get comments likes with one selection.When I doing this and dumping $comment->getLikes() I'm getting object of this type
object(Doctrine\ORM\PersistentCollection)
When try to do something like this $comment->getLikes()->first() getting
Undefined index:commentId
So I cant get likes from database, am I doing something wrong?And if it is possible explain why its working such way?
Here is comment Entity.
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="comments")
*/
class Comment extends Entity
{
/**
*
* /**
* #Column(type="string", length=255)
* #var string
*/
protected $url;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $description;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #Column(name="lng", type="float")
* #var float
*/
protected $lng;
/**
* #Column(name="lat", type="float")
* #var float
*/
protected $lat;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $tags;
/**
* #var Like
* #OneToMany(targetEntity="Like", mappedBy="commentId")
**/
protected $likes;
/**
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* #return float
*/
public function getLong()
{
return $this->lng;
}
/**
* #param float $lng
*/
public function setLong($lng)
{
$this->lng = $lng;
}
/**
* #return float
*/
public function getLat()
{
return $this->lat;
}
/**
* #param float $lat
*/
public function setLat($lat)
{
$this->lat = $lat;
}
/**
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* #return array()
*/
public function getLikes()
{
return $this->likes;
}
}
an here is Like Entity
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="like")
*/
class Like extends Entity
{
/**
* #Column(name="commentId", type="integer")
* #var int
*/
protected $commentId;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #return int
*/
public function getCommentId()
{
return $this->commentId;
}
/**
* #param int $commentId
*/
public function setCommentId($commentId)
{
$this->commentId = $commentId;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
}
class Comment
{
/**
* #Id
* #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $url;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $description;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #Column(name="lng", type="float")
* #var float
*/
protected $lng;
/**
* #Column(name="lat", type="float")
* #var float
*/
protected $lat;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $tags;
/**
* #OneToMany(targetEntity="Like", mappedBy="comment")
*/
protected $likes;
public function __construct()
{
$this->likes = new ArrayCollection();
}
/**
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* #return float
*/
public function getLong()
{
return $this->lng;
}
/**
* #param float $lng
*/
public function setLong($lng)
{
$this->lng = $lng;
}
/**
* #return float
*/
public function getLat()
{
return $this->lat;
}
/**
* #param float $lat
*/
public function setLat($lat)
{
$this->lat = $lat;
}
/**
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* #param Like $like
*/
public function addLike(Like $like)
{
$this->likes->add($like);
$like->setComment($this);
}
/**
* #return ArrayCollection
*/
public function getLikes()
{
return $this->likes;
}
}
/**
* #Entity
* #Table(name="likes")
*/
class Like
{
/**
* #Id
* #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #ManyToOne(targetEntity="Comment", inversedBy="likes")
*/
protected $comment;
/**
* #param mixed $comment
*/
public function setComment(Comment $comment)
{
$this->comment = $comment;
}
/**
* #Column(name="userId", type="integer")
*/
protected $userId;
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
}
FYI : Change like to likes or others because mysql keyword LIKE

Doctrine 2 perform insert, update on entity locally but fails without error on staging

I have an entity called DoerTrip
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Doer Trip
*
* #ORM\Table(name="doer_trip")
* #ORM\Entity
*/
class DoerTrip extends AbstractEntity
{
const STATUS_PUBLISHED = 1;
const STATUS_UNPUBLISHED = 0;
/**
* #var integer
*
* #ORM\Column(name="`id`", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var \Application\Entity\Doer
*
* #ORM\ManyToOne(targetEntity="Doer")
* #ORM\JoinColumn(name="`doer_id`", referencedColumnName="id")
*/
protected $doer; // inversedBy="trips"
/**
* #var \Application\Entity\Trip
*
* #ORM\ManyToOne(targetEntity="Trip")
* #ORM\JoinColumn(name="`trip_id`", referencedColumnName="id")
*/
protected $trip; //inversedBy="doers"
/**
* #var bool
*
* #ORM\Column(name="`published`", type="boolean")
*/
protected $published;
/**
* #var string
*
* #ORM\Column(name="`comment`", type="text")
*/
protected $comment;
/**
* #var integer
*
* #ORM\Column(name="`target_sum`", type="integer")
*/
protected $targetSum;
public function __construct()
{
$this->published = false;
}
/**
* #param string $comment
* #return $this
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* #param \Application\Entity\Doer $doer
* #return $this
*/
public function setDoer(Doer $doer)
{
$this->doer = $doer;
return $this;
}
/**
* #return \Application\Entity\Doer
*/
public function getDoer()
{
return $this->doer;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param boolean $published
* #return $this
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* #param \Application\Entity\Trip $trip
* #return $this
*/
public function setTrip(Trip $trip)
{
$this->trip = $trip;
return $this;
}
/**
* #return \Application\Entity\Trip
*/
public function getTrip()
{
return $this->trip;
}
/**
* #param int $targetSum
* #return $this
*/
public function setTargetSum($targetSum)
{
$this->targetSum = $targetSum;
return $this;
}
/**
* #return int
*/
public function getTargetSum()
{
return (null !== $this->targetSum) ? $this->targetSum : $this->getTrip()->getTargetAmount();
}
}
here Trip Entity:
namespace Application\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Zend\Validator\IsInstanceOf;
/**
* Trip
*
* #ORM\Table(name="trip")
* #ORM\Entity
*/
class Trip extends AbstractEntity
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #var Collection
*
* #ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
* #ORM\JoinTable(name="trip_media",
* joinColumns={#ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
* )
*/
protected $media;
/**
* #var \Application\Entity\Media
*
* #ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
*/
protected $mainMedia;
/**
* #var string
*
* #ORM\Column(name="api_key", type="string", length=255)
*/
protected $apiKey;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=255, nullable=true)
*/
protected $country;
/**
* #var \DateTime
*
* #ORM\Column(name="departure_date", type="date", nullable=true)
*/
protected $departureDate;
/**
* #var \DateTime
*
* #ORM\Column(name="due_date", type="date", nullable=true)
*/
protected $dueDate;
/**
* #var \DateTime
*
* #ORM\Column(name="return_date", type="date", nullable=true)
*/
protected $returnDate;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="target_amount", type="integer")
*/
protected $targetAmount;
/**
* #var Collection
*
* #ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
*/
protected $doers;
/**
* #var Organization
*
* #ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
*/
protected $organization;
/**
* #var Cause
*
* #ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
* #ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $cause;
/**
* #var integer
*
* #ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
*/
protected $status;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var Transaction
*
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
*/
protected $transactions;
/**
* #param Organization $organization
* #return $this
*/
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
return $this;
}
/**
* #return Organization
*/
public function getOrganization()
{
return $this->organization;
}
public function __construct()
{
$this->doers = new ArrayCollection();
$this->media = new ArrayCollection();
$this->status = self::STATUS_ACTIVE;
$this->transactions = new ArrayCollection();
$this->targetAmount = 0;
$this->description = '';
}
/**
* #param string $apiKey
* #return $this
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
return $this;
}
/**
* #return string
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param string $country
* #return $this
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* #param string $description
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param \DateTime $dueDate
* #return $this
*/
public function setDueDate(\DateTime $dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \DateTime $departureDate
* #return $this
*/
public function setDepartureDate(\DateTime $departureDate)
{
$this->departureDate = $departureDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDepartureDate()
{
return $this->departureDate;
}
/**
* #param string $targetAmount
* #return $this
*/
public function setTargetAmount($targetAmount)
{
$this->targetAmount = $targetAmount;
return $this;
}
/**
* #return string
*/
public function getTargetAmount()
{
return $this->targetAmount;
}
/**
* #param string $name
* #return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param int $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* #param \Application\Entity\Cause $cause
* #return $this
*/
public function setCause($cause)
{
$this->cause = $cause;
return $this;
}
/**
* #return \Application\Entity\Cause
*/
public function getCause()
{
return $this->cause;
}
/**
* #param \Doctrine\Common\Collections\Collection $media
* #return $this
*/
public function setMedia($media)
{
$this->media = $media;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getMedia()
{
return $this->media;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function addDoer(DoerTrip $doer)
{
$this->doers->add($doer);
$doer->setTrip($this);
return $this;
}
/**
* #param Collection $doers
* #return $this
*/
public function setDoers(Collection $doers)
{
$this->doers = $doers;
return $this;
}
/**
* #return Collection
*/
public function getDoers()
{
return $this->doers;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function removeDoer(DoerTrip $doer)
{
$this->doers->removeElement($doer);
return $this;
}
/**
* #param \Doctrine\Common\Collections\Collection $transactions
* #return $this
*/
public function setTransactions($transactions)
{
$this->transactions = $transactions;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getTransactions()
{
return $this->transactions;
}
/**
* #param array $data
* #return $this
*/
public function populate(array $data)
{
if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
$data['departureDate'] = new \DateTime($data['departureDate']);
}
if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
$data['dueDate'] = new \DateTime($data['dueDate']);
}
if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
$data['returnDate'] = new \DateTime($data['returnDate']);
}
parent::populate($data);
return $this;
}
/**
* #param \DateTime $returnDate
* #return $this
*/
public function setReturnDate(\DateTime $returnDate)
{
$this->returnDate = $returnDate;
return $this;
}
/**
* #return \DateTime
*/
public function getReturnDate()
{
return $this->returnDate;
}
/**
* #param \Application\Entity\Media $mainMedia
* #return $this
*/
public function setMainMedia($mainMedia)
{
$this->mainMedia = $mainMedia;
return $this;
}
/**
* #return \Application\Entity\Media
*/
public function getMainMedia()
{
return $this->mainMedia;
}
/**
* #param Media $media
* #return bool
*/
public function hasMedia(Media $media)
{
return $this->getMedia()->contains($media);
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function addMedia(Media $media)
{
$this->media->add($media);
return $this;
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function removeMedia(Media $media)
{
$this->media->removeElement($media);
return $this;
}
}
Here is Doer Entity
namespace Application\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Zend\Validator\IsInstanceOf;
/**
* Trip
*
* #ORM\Table(name="trip")
* #ORM\Entity
*/
class Trip extends AbstractEntity
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #var Collection
*
* #ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
* #ORM\JoinTable(name="trip_media",
* joinColumns={#ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
* )
*/
protected $media;
/**
* #var \Application\Entity\Media
*
* #ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
*/
protected $mainMedia;
/**
* #var string
*
* #ORM\Column(name="api_key", type="string", length=255)
*/
protected $apiKey;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=255, nullable=true)
*/
protected $country;
/**
* #var \DateTime
*
* #ORM\Column(name="departure_date", type="date", nullable=true)
*/
protected $departureDate;
/**
* #var \DateTime
*
* #ORM\Column(name="due_date", type="date", nullable=true)
*/
protected $dueDate;
/**
* #var \DateTime
*
* #ORM\Column(name="return_date", type="date", nullable=true)
*/
protected $returnDate;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="target_amount", type="integer")
*/
protected $targetAmount;
/**
* #var Collection
*
* #ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
*/
protected $doers;
/**
* #var Organization
*
* #ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
*/
protected $organization;
/**
* #var Cause
*
* #ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
* #ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $cause;
/**
* #var integer
*
* #ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
*/
protected $status;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var Transaction
*
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
*/
protected $transactions;
/**
* #param Organization $organization
* #return $this
*/
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
return $this;
}
/**
* #return Organization
*/
public function getOrganization()
{
return $this->organization;
}
public function __construct()
{
$this->doers = new ArrayCollection();
$this->media = new ArrayCollection();
$this->status = self::STATUS_ACTIVE;
$this->transactions = new ArrayCollection();
$this->targetAmount = 0;
$this->description = '';
}
/**
* #param string $apiKey
* #return $this
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
return $this;
}
/**
* #return string
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param string $country
* #return $this
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* #param string $description
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param \DateTime $dueDate
* #return $this
*/
public function setDueDate(\DateTime $dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \DateTime $departureDate
* #return $this
*/
public function setDepartureDate(\DateTime $departureDate)
{
$this->departureDate = $departureDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDepartureDate()
{
return $this->departureDate;
}
/**
* #param string $targetAmount
* #return $this
*/
public function setTargetAmount($targetAmount)
{
$this->targetAmount = $targetAmount;
return $this;
}
/**
* #return string
*/
public function getTargetAmount()
{
return $this->targetAmount;
}
/**
* #param string $name
* #return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param int $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* #param \Application\Entity\Cause $cause
* #return $this
*/
public function setCause($cause)
{
$this->cause = $cause;
return $this;
}
/**
* #return \Application\Entity\Cause
*/
public function getCause()
{
return $this->cause;
}
/**
* #param \Doctrine\Common\Collections\Collection $media
* #return $this
*/
public function setMedia($media)
{
$this->media = $media;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getMedia()
{
return $this->media;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function addDoer(DoerTrip $doer)
{
$this->doers->add($doer);
$doer->setTrip($this);
return $this;
}
/**
* #param Collection $doers
* #return $this
*/
public function setDoers(Collection $doers)
{
$this->doers = $doers;
return $this;
}
/**
* #return Collection
*/
public function getDoers()
{
return $this->doers;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function removeDoer(DoerTrip $doer)
{
$this->doers->removeElement($doer);
return $this;
}
/**
* #param \Doctrine\Common\Collections\Collection $transactions
* #return $this
*/
public function setTransactions($transactions)
{
$this->transactions = $transactions;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getTransactions()
{
return $this->transactions;
}
/**
* #param array $data
* #return $this
*/
public function populate(array $data)
{
if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
$data['departureDate'] = new \DateTime($data['departureDate']);
}
if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
$data['dueDate'] = new \DateTime($data['dueDate']);
}
if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
$data['returnDate'] = new \DateTime($data['returnDate']);
}
parent::populate($data);
return $this;
}
/**
* #param \DateTime $returnDate
* #return $this
*/
public function setReturnDate(\DateTime $returnDate)
{
$this->returnDate = $returnDate;
return $this;
}
/**
* #return \DateTime
*/
public function getReturnDate()
{
return $this->returnDate;
}
/**
* #param \Application\Entity\Media $mainMedia
* #return $this
*/
public function setMainMedia($mainMedia)
{
$this->mainMedia = $mainMedia;
return $this;
}
/**
* #return \Application\Entity\Media
*/
public function getMainMedia()
{
return $this->mainMedia;
}
/**
* #param Media $media
* #return bool
*/
public function hasMedia(Media $media)
{
return $this->getMedia()->contains($media);
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function addMedia(Media $media)
{
$this->media->add($media);
return $this;
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function removeMedia(Media $media)
{
$this->media->removeElement($media);
return $this;
}
}
I perform this sample of code:
$doerTrip = new DoerTrip();
$doerTrip->setDoer($doer)->setTrip($trip);
$em->persist($doerTrip);
$em->flush();
locally it works (on Windows). But on staging (Ubuntu) new record is not created and I don't get any errors. Update of the entity DoerTrip on staging doesn't work too.
If I perform insert with the help of connection something like this
$stmt = $conn->prepare('INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)');
$stmt->bindParam(1, $param);
...
everything works fine.
When using ORM in SQL Logger I can see
START TRANSACTION;
INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)
COMMIT;
but new record is not created on staging.
locally everything works fine.
I don't know maybe it depends on MySQL configuration.
I have no idea.
Here my doer_trip table
CREATE TABLE `doer_trip` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`doer_id` INT(11) NOT NULL,
`trip_id` INT(11) UNSIGNED NOT NULL,
`published` INT(1) UNSIGNED NOT NULL DEFAULT '0',
`comment` TEXT NULL,
`target_sum` INT(10) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `doer_id` (`doer_id`),
INDEX `trip_id` (`trip_id`),
UNIQUE INDEX `doer_iduniq` (`doer_id`, `trip_id`),
CONSTRAINT `FK_doer_trip_trip` FOREIGN KEY (`trip_id`) REFERENCES `trip` (`id`),
CONSTRAINT `FK_doer_trip_doer` FOREIGN KEY (`doer_id`) REFERENCES `doer` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=41
The problem was in
/**
* #var bool
*
* #ORM\Column(name="`published`", type="boolean")
*/
protected $published;
If I set type to integer like this
/**
* #var integer
*
* #ORM\Column(name="`published`", type="integer")
*/
protected $published;
Everything work fine. But why it works fine on my local environment???

Categories