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
Related
I can't not generate fixtures in my symfony project.
Previoucly, I had a attribute OnetoMany and i passed to ManytoMany.
I think that error comes from here.
I generate my fixtures with alice fixtures bundle : https://github.com/hautelook/AliceBundle
I use this commande :
./bin/console hautelook:fixtures:load --no-interaction --purge-with-truncate
This result :
Neither the property "productType" nor one of the methods "getProductType()", "productType()", "isProductType()", "hasProductType()", "__get()" exist and have public access in class "App\Entity\Product".
My concerned entity :
<?php
declare(strict_types = 1);
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Annotation\Cached;
use App\Traits\ContentEntityTrait;
use App\Traits\SeoTrait;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinTable;
use Exception;
use JsonSerializable;
use Serializable;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Class Product
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="App\Repository\ProductRepository")
*
* #Vich\Uploadable
* #Cached()
*
* #SuppressWarnings(PHPMD.TooManyFields)
*/
class Product implements Serializable, JsonSerializable
{
use ContentEntityTrait;
use SeoTrait;
//<editor-fold desc="Members">
/**
* #var string
*
* #ORM\Column(type="text")
*
* #Assert\NotBlank()
*/
protected $description;
/**
* #var string
*
* #ORM\Column(type="string", nullable=true)
*/
protected $packaging;
/**
* #var string
*
* #ORM\Column(type="string", nullable=true)
*/
protected $packing;
/**
* #var string
*
* #ORM\Column(type="string", nullable=true)
*/
protected $gencod;
/**
* #Vich\UploadableField(mapping="product_picture", fileNameProperty="picture")
*
* #Assert\Image(mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* })
*
* #var File
*/
protected $pictureFile;
/**
* #var string
*
* #Assert\Length(max=100)
*
* #ORM\Column(type="string", length=100)
*/
protected $picture;
/**
* #var string
*
* #Assert\Length(max=255)
*
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $pdf;
/**
* #var File
*
* #Assert\File(mimeTypes = {"application/pdf", "application/x-pdf"})
*
* #Vich\UploadableField(mapping="product_pdf", fileNameProperty="pdf")
*/
protected $pdfFile;
/**
* #var Brand
*
* #ORM\ManyToOne(targetEntity="App\Entity\Brand", inversedBy="products")
*/
protected $brand;
/**
* #var Collection|ProductType[]
* #Assert\Count(min=1, minMessage="Il faut sélectionner au moins {{ limit }} élément")
* #ORM\ManyToMany(targetEntity="App\Entity\Product", inversedBy="products")
* #JoinTable(name="product_product_type")
*/
protected $productTypes;
/**
* #var Collection|Sector[]
*
* #Assert\Count(min=1, minMessage="Il faut sélectionner au moins {{ limit }} élément")
*
* #ORM\ManyToMany(targetEntity="App\Entity\Sector")
*/
protected $sectors;
/**
* #var GemRcn[]
*
* #Assert\Count(min=1, minMessage="Il faut sélectionner au moins {{ limit }} élément")
*
* #ORM\ManyToMany(targetEntity="App\Entity\GemRcn", inversedBy="products")
*/
protected $gemRcns;
/**
* #var Collection|Sample[]
*
* #ORM\OneToMany(targetEntity="App\Entity\Sample", mappedBy="product", cascade={"remove"})
*/
protected $samples;
/**
* #var Collection|Product[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\Product")
*/
protected $products;
/**
* #var Collection|Inspiration[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\Inspiration")
*/
protected $inspirations;
/**
* #var Collection|Product[]
* Many Product have many Product.
* #ORM\ManyToMany(targetEntity="App\Entity\Product")
* #ORM\JoinTable(name="product_scoring",
* joinColumns={#ORM\JoinColumn(name="current_product", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="next_product", referencedColumnName="id")}
* )
*/
protected $scoring;
/**
* #var User[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\User", mappedBy="products")
*/
protected $users;
/**
* #var bool
*
* #ORM\Column(type="boolean", options={"default": true})
*/
protected $enabled = true;
/**
* #var bool
*
* Field not mapped
*/
protected $favorite = false;
/**
* #var string
*
* Field not mapped
*/
protected $picturePath;
/**
* #var string
*
* Field not mapped
*/
protected $previewPath;
//</editor-fold>
/**
* Product constructor.
*/
public function __construct()
{
$this->sectors = new ArrayCollection();
$this->productTypes = new ArrayCollection();
$this->samples = new ArrayCollection();
$this->products = new ArrayCollection();
$this->users = new ArrayCollection();
$this->gemRcns = new ArrayCollection();
$this->scoring = new ArrayCollection();
}
/**
* #param User $user
*
* #return bool
*/
public function toggleUser(User $user): bool
{
if ($this->isFavorite($user)) {
$this->removeUser($user);
return false;
}
$this->addUser($user);
return true;
}
/**
* #param User $user
*
* #return bool
*/
public function isFavorite(?User $user): bool
{
return $this->users->contains($user);
}
/**
* {#inheritdoc}
*/
public function jsonSerialize(): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'packaging' => $this->packaging,
'brand' => $this->brand->__toString(),
'isFavorite' => $this->favorite,
'picturePath' => $this->picturePath,
'previewPath' => $this->previewPath,
'picture' => $this->picture
];
}
/**
* {#inheritdoc}
*/
public function serialize()
{
return serialize([
$this->id,
$this->title,
$this->slug,
]);
}
/**
* {#inheritdoc}
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->title,
$this->slug,
) = unserialize($serialized, ['allowed_classes' => true]);
}
//<editor-fold desc="Getters">
/**
* #return null|File
*/
public function getPictureFile(): ?File
{
return $this->pictureFile;
}
/**
* #return null|string
*/
public function getPicture(): ?string
{
return $this->picture;
}
/**
* #return string
*/
public function getPdf(): ?string
{
return $this->pdf;
}
/**
* #return File
*/
public function getPdfFile(): ?File
{
return $this->pdfFile;
}
/**
* #return string
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* #return string
*/
public function getPackaging(): ?string
{
return $this->packaging;
}
/**
* #return string
*/
public function getPacking(): ?string
{
return $this->packing;
}
/**
* #return string
*/
public function getGencod(): ?string
{
return $this->gencod;
}
/**
* #return Brand
*/
public function getBrand(): ?Brand
{
return $this->brand;
}
/**
* #return ProductType[]|Collection
*/
public function getProductTypes(): Collection
{
return $this->productTypes;
}
/**
* #return Sector[]|Collection
*/
public function getSectors(): Collection
{
return $this->sectors;
}
/**
* #return Product[]|Collection
*/
public function getProducts(): Collection
{
return $this->products;
}
/**
* #return GemRcn[]|Collection
*/
public function getGemRcns(): Collection
{
return $this->gemRcns;
}
/**
* #return bool
*/
public function isEnabled(): bool
{
return $this->enabled;
}
//</editor-fold>
//<editor-fold desc="Setters">
/**
* #param string $picture
*
* #return static
*/
public function setPicture(?string $picture): self
{
$this->picture = $picture;
return $this;
}
/**
* #param File $pictureFile
*
* #return static
* #throws Exception
*/
public function setPictureFile(?File $pictureFile): self
{
$this->pictureFile = $pictureFile;
if ($pictureFile instanceof UploadedFile && $pictureFile->getError() === 0) {
$this->updatedAt = new DateTime();
}
return $this;
}
/**
* #param string $pdf
*
* #return self
*/
public function setPdf(?string $pdf): self
{
$this->pdf = $pdf;
return $this;
}
/**
* #param File $pdfFile
*
* #return self
* #throws Exception
*/
public function setPdfFile(?File $pdfFile): self
{
$this->pdfFile = $pdfFile;
if ($pdfFile instanceof UploadedFile && $pdfFile->getError() === 0) {
$this->updatedAt = new DateTime();
}
return $this;
}
/**
* #param string $description
*
* #return self
*/
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
/**
* #param string $packaging
*
* #return self
*/
public function setPackaging(string $packaging): self
{
$this->packaging = $packaging;
return $this;
}
/**
* #param string $packing
*
* #return self
*/
public function setPacking(string $packing): self
{
$this->packing = $packing;
return $this;
}
/**
* #param string $gencod
*
* #return self
*/
public function setGencod(string $gencod): self
{
$this->gencod = $gencod;
return $this;
}
/**
* #param Brand $brand
*
* #return self
*/
public function setBrand(Brand $brand): self
{
$this->brand = $brand;
return $this;
}
/**
* #param ProductType $productType
*
* #return self
*/
public function addProductType(ProductType $productType): self
{
$this->productTypes->add($productType);
return $this;
}
/**
* #param bool $enabled
*
* #return self
*/
public function setEnabled(bool $enabled): self
{
$this->enabled = $enabled;
return $this;
}
/**
* #param bool $isFavorite
*
* #return self
*/
public function setFavorite(bool $isFavorite): self
{
$this->favorite = $isFavorite;
return $this;
}
/**
* #param string $path
*
* #return self
*/
public function setPicturePath(string $path): self
{
$this->picturePath = $path;
return $this;
}
/**
* #param string $path
*
* #return self
*/
public function setPreviewPath(string $path): self
{
$this->previewPath = $path;
return $this;
}
//</editor-fold>
//<editor-fold desc="Collection">
/**
* #param Sector $sector
*
* #return self
*/
public function removeSector(Sector $sector): self
{
$this->sectors->removeElement($sector);
return $this;
}
/**
* #param ProductType $productType
*
* #return self
*/
public function removeProductType(ProductType $productType): self
{
$this->productTypes->removeElement($productType);
return $this;
}
/**
* #param Sector $sector
*
* #return self
*/
public function addSector(Sector $sector): self
{
$this->sectors->add($sector);
return $this;
}
/**
* #param Sample $sample
*
* #return self
*/
public function removeSample(Sample $sample): self
{
$this->samples->removeElement($sample);
return $this;
}
/**
* #param Sample $sample
*
* #return self
*/
public function addSample(Sample $sample): self
{
$this->samples->add($sample);
return $this;
}
/**
* #param Product $product
*
* #return self
*/
public function removeProduct(Product $product): self
{
$this->products->removeElement($product);
return $this;
}
/**
* #param Product $product
*
* #return self
*/
public function addProduct(Product $product): self
{
$this->products->add($product);
return $this;
}
/**
* #param User $user
*
* #return self
*/
public function addUser(User $user): self
{
$this->users->add($user);
$user->addProduct($this);
return $this;
}
/**
* #param User $user
*
* #return self
*/
public function removeUser(User $user): self
{
$this->users->removeElement($user);
$user->removeProduct($this);
return $this;
}
/**
* #param GemRcn $gemRcn
*
* #return self
*/
public function addGemRcn(GemRcn $gemRcn): self
{
$this->gemRcns->add($gemRcn);
$gemRcn->addProduct($this);
return $this;
}
/**
* #param GemRcn $gemRcn
*
* #return self
*/
public function removeGemRcn(GemRcn $gemRcn): self
{
$this->gemRcns->removeElement($gemRcn);
$gemRcn->removeProduct($this);
return $this;
}
public function getScoring(){
return $this->scoring;
}
/**
* #param Product $product
* #return Product
*/
public function addScoring(Product $product) :self
{
$this->scoring->add($product);
return $this;
}
/**
* #param Product $product
* #return self
*/
public function removeScoring(Product $product): self
{
$this->scoring->removeElement($product);
return $this;
}
}
My other entity (ManytoMany) :
<?php
declare(strict_types = 1);
namespace App\Entity;
use App\Annotation\Cached;
use App\Traits\ContentEntityTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Class ProductType
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="App\Repository\ProductTypeRepository")
*
* #UniqueEntity(fields={"title", "universe"})
*
* #Cached()
*/
class ProductType implements \JsonSerializable
{
use ContentEntityTrait;
//<editor-fold desc="Members">
/**
* #var Universe
*
* #ORM\ManyToOne(targetEntity="App\Entity\Universe", inversedBy="productTypes", cascade={"persist"})
*/
protected $universe;
/**
* #var Product[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\Product", mappedBy="productTypes", cascade={"remove"})
*/
protected $products;
//</editor-fold>
/**
* Product Type constructor.
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* {#inheritdoc}
*/
public function jsonSerialize(): array
{
return [
'id' => $this->id,
'title' => $this->title,
];
}
//<editor-fold desc="Getters">
/**
* #return Product[]
*/
public function getProducts()
{
return $this->products;
}
/**
* #return Universe
*/
public function getUniverse(): ?Universe
{
return $this->universe;
}
//</editor-fold>
//<editor-fold desc="Setters">
/**
* #param Universe $universe
*
* #return self
*/
public function setUniverse(Universe $universe): self
{
$this->universe = $universe;
$universe->addProductType($this);
return $this;
}
//</editor-fold>
//<editor-fold desc="Collection">
/**
* #param Product $product
*
* #return self
*/
public function addProduct(Product $product): self
{
$this->products->add($product);
return $this;
}
/**
* #param Product $product
*
* #return self
*/
public function removeProduct(Product $product): self
{
$this->products->removeElement($product);
return $this;
}
//</editor-fold>
}
My fixtures yaml :
App\Entity\Product:
product_{1..40}:
title: '<sentence(3)>'
description: '<sentence()>'
packaging: '<sentence(3)>'
packing: '<sentence(3)>'
picture: '<fileCopy("features/files/image/test-picture.jpg","public/uploads/products", 0)>'
brand: '#brand_<numberBetween(1, 10)>'
gemRcns: ['#gem_rcn_<numberBetween(1, 10)>']
gencod: '<sentence(3)>'
productTypes: ['#product_type_<numberBetween(1, 21)>','#product_type_<numberBetween(1, 21)>']
sectors: ['#school', '#health' ,'#pension', '#company', '#bakery', '#hostel', '#retailer']
I'm trying to encode the password in symfony3 but i'm facing some problems.
this is the error i got.
Catchable Fatal Error: Argument 3 passed to GMAOBundle\Security\LoginFormAuthentificator::__construct() must be an instance of Symfony\Component\Security\Core\Encoder\UserPasswordEncoder, none given, called in C:\xampp\htdocs\ProjetSomadiag\var\cache\dev\appDevDebugProjectContainer.php on line 483 and defined
I'm working with guard in the authentification.
this is the authentification class name loginformauthentificator.
namespace GMAOBundle\Security;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
class LoginFormAuthentificator extends AbstractGuardAuthenticator
{
private $em;
private $router;
private $passwordEncoder;
public function __construct($em, $router,UserPasswordEncoder $PasswordEncoder )
{
$this->em = $em;
$this->router = $router;
//$this->passwordEncoder = new UserPasswordEncoder();
$this->passwordEncoder = $PasswordEncoder;
}
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
return;
}
$request->getSession()->set(Security::LAST_USERNAME,$request->request->get('_username'));
return [
'username' => $request->request->get('_username'),
'password' => $request->request->get('_password'),
];
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
return $this->em->getRepository('GMAOBundle:Employe')
->findOneBy(['EmailEmploye' => $username]);
}
/**
* #param mixed $credentials
* #param UserInterface $user
* #return bool
*/
public function checkCredentials($credentials, UserInterface $user)
{
$password=$credentials['password'];
if ($this->passwordEncoder->isPasswordValid($user, $password)) {
return true;
}
return false;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$url = $this->router->generate('gmao_homepage');
return new RedirectResponse($url);
}
public function supportsRememberMe()
{
return true;
}
public function start(Request $request, AuthenticationException $authException = null)
{
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
}
and this is the user class.
namespace GMAOBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity
* #ORM\Table(name="employe")
*/
class Employe implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/private $idEmploye;
/**
* #ORM\Column(type="string")
*/private $NomEmploye;
/**
* #ORM\Column(type="string")
*/private $PrenomEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateNaissanceEmploye;
/**
* #ORM\Column(type="string")
*/private $cinEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $AdresseEmploye;
/**
* #ORM\Column(type="string")
*/private $MatriculeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SituationFamiliale;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SexeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $CnssEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $FonctionEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroMutuelle;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateDebutEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateTitularisationEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroTelEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroLigneEmploye;
/**
* #ORM\Column(type="string")
*/private $EmailEmploye;
/**
* A non-persisted field that's used to create the encoded password.
* #var string
*/private $plainPassword;
/**
* #ORM\Column(type="string")
*/private $MdpEmploye;
/**
* #ORM\Column(type="string")
*/private $active;
/**
* #ORM\Column(type="json_array")
*/private $roles = [];
/**
* #ORM\ManyToOne(targetEntity="Departement")
* #ORM\JoinColumn(name="Departement",
referencedColumnName="id_departement")
*/private $Departement;
/**
* #ORM\ManyToOne(targetEntity="Equipe", cascade={"persist"})
* #ORM\JoinColumn(name="Equipe", referencedColumnName="id" ,nullable=true)
*/private $equipe;
/**
* #ORM\Column(type="string", nullable=true)
*/private $imgsrc;
/**
* #ORM\Column(type="string")
*private $responsable_projet;
/**
* #ORM\Column(type="string")
*private $m_GMAO_Projet;
/**
* #ORM\Column(type="string")
*public $m_PMP_Objectif;
/**
* #ORM\Column(type="string")
*public $m_Services;*/
/**
* User Interface Methode Override
*/
function __construct()
{
}
function __destruct()
{
}
public function getUsername()
{
return $this->EmailEmploye;
}
public function getRoles()
{
$roles = $this->roles;
if(!in_array('ROLE_USER',$roles))
{
$roles[]='ROLE_USER';
}
return $roles;
}
public function getPassword()
{
return$this->MdpEmploye;
}
public function getSalt()
{
}
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* GETTERS AND SETTERS
**/
/**
* #return mixed
*/
public function getIdEmploye()
{
return $this->idEmploye;
}
/**
* #param mixed $idEmploye
*/
public function setIdEmploye($idEmploye)
{
$this->idEmploye = $idEmploye;
}
/**
* #return mixed
*/
public function getNomEmploye()
{
return $this->NomEmploye;
}
/**
* #param mixed $NomEmploye
*/
public function setNomEmploye($NomEmploye)
{
$this->NomEmploye = $NomEmploye;
}
/**
* #return mixed
*/
public function getPrenomEmploye()
{
return $this->PrenomEmploye;
}
/**
* #param mixed $PrenomEmploye
*/
public function setPrenomEmploye($PrenomEmploye)
{
$this->PrenomEmploye = $PrenomEmploye;
}
/**
* #return mixed
*/
public function getDateNaissanceEmploye()
{
return $this->DateNaissanceEmploye;
}
/**
* #param mixed $DateNaissanceEmploye
*/
public function setDateNaissanceEmploye($DateNaissanceEmploye)
{
$this->DateNaissanceEmploye = $DateNaissanceEmploye;
}
/**
* #return mixed
*/
public function getcinEmploye()
{
return $this->cinEmploye;
}
/**
* #param mixed $cinemploye
*/
public function setcinEmploye($Cinemploye)
{
$this->cinEmploye = $Cinemploye;
}
/**
* #return mixed
*/
public function getAdresseEmploye()
{
return $this->AdresseEmploye;
}
/**
* #param mixed $AdresseEmploye
*/
public function setAdresseEmploye($AdresseEmploye)
{
$this->AdresseEmploye = $AdresseEmploye;
}
/**
* #return mixed
*/
public function getMatriculeEmploye()
{
return $this->MatriculeEmploye;
}
/**
* #param mixed $MatriculeEmploye
*/
public function setMatriculeEmploye($MatriculeEmploye)
{
$this->MatriculeEmploye = $MatriculeEmploye;
}
/**
* #return mixed
*/
public function getSituationFamiliale()
{
return $this->SituationFamiliale;
}
/**
* #param mixed $SituationFamiliale
*/
public function setSituationFamiliale($SituationFamiliale)
{
$this->SituationFamiliale = $SituationFamiliale;
}
/**
* #return mixed
*/
public function getSexeEmploye()
{
return $this->SexeEmploye;
}
/**
* #param mixed $SexeEmploye
*/
public function setSexeEmploye($SexeEmploye)
{
$this->SexeEmploye = $SexeEmploye;
}
/**
* #return mixed
*/
public function getCnssEmploye()
{
return $this->CnssEmploye;
}
/**
* #param mixed $CnssEmploye
*/
public function setCnssEmploye($CnssEmploye)
{
$this->CnssEmploye = $CnssEmploye;
}
/**
* #return mixed
*/
public function getFonctionEmploye()
{
return $this->FonctionEmploye;
}
/**
* #param mixed $FonctionEmploye
*/
public function setFonctionEmploye($FonctionEmploye)
{
$this->FonctionEmploye = $FonctionEmploye;
}
/**
* #return mixed
*/
public function getNumeroMutuelle()
{
return $this->NumeroMutuelle;
}
/**
* #param mixed $NumeroMutuelle
*/
public function setNumeroMutuelle($NumeroMutuelle)
{
$this->NumeroMutuelle = $NumeroMutuelle;
}
/**
* #return mixed
*/
public function getDateDebutEmploye()
{
return $this->DateDebutEmploye;
}
/**
* #param mixed $DateDebutEmploye
*/
public function setDateDebutEmploye($DateDebutEmploye)
{
$this->DateDebutEmploye = $DateDebutEmploye;
}
/**
* #return mixed
*/
public function getDateTitularisationEmploye()
{
return $this->DateTitularisationEmploye;
}
/**
* #param mixed $DateTitularisationEmploye
*/
public function setDateTitularisationEmploye($DateTitularisationEmploye)
{
$this->DateTitularisationEmploye = $DateTitularisationEmploye;
}
/**
* #return mixed
*/
public function getNumeroTelEmploye()
{
return $this->NumeroTelEmploye;
}
/**
* #param mixed $NumeroTelTmploye
*/
public function setNumeroTelEmploye($NumeroTelEmploye)
{
$this->NumeroTelEmploye = $NumeroTelEmploye;
}
/**
* #return mixed
*/
public function getNumeroLigneEmploye()
{
return $this->NumeroLigneEmploye;
}
/**
* #param mixed $NumeroLigneEmploye
*/
public function setNumeroLigneEmploye($NumeroLigneEmploye)
{
$this->NumeroLigneEmploye = $NumeroLigneEmploye;
}
/**
* #return mixed
*/
public function getEmailEmploye()
{
return $this->EmailEmploye;
}
/**
* #param mixed $EmailEmploye
*/
public function setEmailEmploye($EmailEmploye)
{
$this->EmailEmploye = $EmailEmploye;
}
/**
* #return mixed
*/
public function getMdpEmploye()
{
return $this->MdpEmploye;
}
/**
* #param mixed $MdpEmploye
*/
public function setMdpEmploye($MdpEmploye)
{
$this->MdpEmploye = $MdpEmploye;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #return mixed
*/
public function getDepartement()
{
return $this->Departement;
}
/**
* #param mixed $Departement
*/
public function setDepartement($Departement)
{
$this->Departement = $Departement;
}
/**
* #return mixed
*/
public function getImgsrc()
{
return $this->imgsrc;
}
/**
* #param mixed $imgsrc
*/
public function setImgsrc($imgsrc)
{
$this->imgsrc = $imgsrc;
}
public function setRoles($roles)
{
$this->roles =$roles;
}
/**
* #return mixed
*/
public function getEquipe()
{
return $this->equipe;
}
/**
* #param mixed $Equipe
*/
public function setEquipe($Equipe)
{
$this->equipe = $Equipe;
}
/**
* #return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* #param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
$this->password = null;
}
}
i don't know what this error stand for.
If you are using dependency injection, you must send your password encoder in as your third argument.
Example:
services.yml
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
arguments:
- "#doctrine.orm.entity_manager"
- "#router"
- "#passwordencoder"
Alternatively you can "autowire".
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
autowire: true
Or however you're using your services.yml to inject dependencies.
If you're creating the loginFormAuthenticator as an object you have to instantiate it as:
$loginAuthenticator = new LoginFormAuthentificator($entitymanager, $router, $passwordEncoder);
You're missing the password encoder in some argument when you call the class.
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
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
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???