I have a little problem with Doctrine and Symfony 5.4. I've searched on StackOverflow and on the doc, but every solution seems that is not correctly for me.
I have 3 class: Lang, State, OrderState. Last one is join with Lang and State through id_state and id_lang with a ManyToMany association relation ship.
When i execute the schema validate, i get the classic error. Honestly i don't understand why.
Mapping
-------
[FAIL] The entity-class App\Entity\OrderState mapping is invalid:
* The referenced column name 'id_state' has to be a primary key column on the target entity class 'App\Entity\OrderState'.
* The referenced column name 'id' has to be a primary key column on the target entity class 'App\Entity\Lang'.
Database
--------
In MissingColumnException.php line 15:
Column name "id_state" referenced for relation from App\Entity\OrderState towa
rds App\Entity\State does not exist.
State.php
<?php
namespace App\Entity;
use App\Repository\StateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=StateRepository::class)
*/
class State
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id_state;
/**
* #ORM\Column(type="string", length=255)
*/
private $label;
public function getIdState(): ?int
{
return $this->id_state;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
}
Lang.php
<?php
namespace App\Entity;
use App\Repository\LangRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=LangRepository::class)
*/
class Lang
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id_lang;
/**
* #ORM\Column(type="string", length=255)
*/
private $lang;
public function getIdLang(): ?int
{
return $this->id_lang;
}
public function setIdLang(int $id_lang): self
{
$this->id_lang = $id_lang;
return $this;
}
public function getLang(): ?string
{
return $this->lang;
}
public function setLang(string $lang): self
{
$this->lang = $lang;
return $this;
}
}
and OrderState.php
<?php
namespace App\Entity;
use App\Repository\OrderStateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=OrderStateRepository::class)
*/
class OrderState
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity=State::class)
* #ORM\JoinColumn(name="id_state", referencedColumnName="id_state")
*/
private $id_state;
/**
* #ORM\ManyToMany(targetEntity=Lang::class)
* #ORM\JoinColumn(name="id_lang", referencedColumnName="id_lang")
*/
private $id_lang;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $state;
public function __construct()
{
$this->id_state = new ArrayCollection();
$this->id_lang = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* #return Collection<int, State>
*/
public function getIdState(): Collection
{
return $this->id_state;
}
public function addIdState(State $idState): self
{
if (!$this->id_state->contains($idState)) {
$this->id_state[] = $idState;
}
return $this;
}
public function removeIdState(State $idState): self
{
$this->id_state->removeElement($idState);
return $this;
}
/**
* #return Collection<int, Lang>
*/
public function getIdLang(): Collection
{
return $this->id_lang;
}
public function addIdLang(Lang $idLang): self
{
if (!$this->id_lang->contains($idLang)) {
$this->id_lang[] = $idLang;
}
return $this;
}
public function removeIdLang(Lang $idLang): self
{
$this->id_lang->removeElement($idLang);
return $this;
}
public function getState(): ?string
{
return $this->state;
}
public function setState(?string $state): self
{
$this->state = $state;
return $this;
}
}
Related
i want to develop a doctrine-powered database application which should portray the following schema.
There are users, companies and relation-roles which describes the relation between a user to a company like [USER X] is [ROLE X] in [COMPANY X].
I'm using the symfony maker-bundle to create the entities I need. I'll attach every code at the end of this post.
To test the code, I persisted a company, a user, a role and a relation between them to the database. I expected that I could get all related users with their roles using a Company-Entity-Object with the generated getter getRelatedUsers() but I get an empty ArrayCollection.
This is how I tested to fetch the data in a TestController
#[Route('/test', name: 'test_page')]
public function index(CompanyRepository $companyRepository): Response
{
$companies = $companyRepository->findAll();
dd($companies[0]->getRelatedUsers());
}
Thanks for your help!
User.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $fullName;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="user")
*/
private $relatedCompanies;
public function __construct()
{
$this->relatedCompanies = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(string $fullName): self
{
$this->fullName = $fullName;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedCompanies(): Collection
{
return $this->relatedCompanies;
}
public function addRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if (!$this->relatedCompanies->contains($relatedCompany)) {
$this->relatedCompanies[] = $relatedCompany;
$relatedCompany->setUser($this);
}
return $this;
}
public function removeRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if ($this->relatedCompanies->removeElement($relatedCompany)) {
// set the owning side to null (unless already changed)
if ($relatedCompany->getUser() === $this) {
$relatedCompany->setUser(null);
}
}
return $this;
}
}
Company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
UserCompanyRelation.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRepository::class)
*/
class UserCompanyRelation
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=UserCompanyRelationRole::class, inversedBy="userCompanyRelations")
* #ORM\JoinColumn(nullable=false)
*/
private $role;
/**
* #ORM\ManyToOne(targetEntity=Company::class, inversedBy="relatedUsers")
* #ORM\JoinColumn(nullable=false)
*/
private $company;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="relatedCompanies")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function __construct()
{
}
public function getId(): ?int
{
return $this->id;
}
public function getRole(): ?UserCompanyRelationRole
{
return $this->role;
}
public function setRole(?UserCompanyRelationRole $role): self
{
$this->role = $role;
return $this;
}
public function getCompany(): ?Company
{
return $this->company;
}
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
UserCompanyRelationRole.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRoleRepository::class)
*/
class UserCompanyRelationRole
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="role")
*/
private $userCompanyRelations;
public function __construct()
{
$this->userCompanyRelations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getUserCompanyRelations(): Collection
{
return $this->userCompanyRelations;
}
public function addUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if (!$this->userCompanyRelations->contains($userCompanyRelation)) {
$this->userCompanyRelations[] = $userCompanyRelation;
$userCompanyRelation->setRole($this);
}
return $this;
}
public function removeUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if ($this->userCompanyRelations->removeElement($userCompanyRelation)) {
// set the owning side to null (unless already changed)
if ($userCompanyRelation->getRole() === $this) {
$userCompanyRelation->setRole(null);
}
}
return $this;
}
}
I found an solution. I had to modify the fetch-strategy to EAGER in a annotation attribute. I modified the relatedUsers annotation property in company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company", fetch="EAGER")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
You should use inversed by for bidirectional mapping between entities. See: https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/association-mapping.html#many-to-many-bidirectional
I am trying to implement KnpLabs / DoctrineBehaviors / Translatable in Symfony 5.2.
I have implemented two entities for translation as described in the docs, however, Symfony throws the following error:
Error: Class App\Entity\BlogPost contains 11 abstract methods and must therefore be declared abstract or implement the remaining methods (Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface::getTranslations, Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface::getNewTranslations, Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface::addTranslation, ...)
When I declare that class "abstract", I am getting the following error:
Trying to invoke abstract method Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface::getTranslationEntityClass()
How can I solve this problem?
Entity BlogPost
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
/**
* #ORM\Entity
*/
abstract class BlogPost implements TranslatableInterface
{
use TranslationTrait;
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $active;
public function getId(): ?int
{
return $this->id;
}
public function getActive(): ?int
{
return $this->id;
}
public function setActive(int $active): self
{
$this->active = $active;
return $this;
}
}
Entity BlogPostTranslation
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
/**
* #ORM\Entity
*/
class BlogPostTranslation implements TranslationInterface
{
use TranslationTrait;
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="string", length=255)
*/
protected $title;
/**
* #ORM\Column(type="string", length=100)
*/
protected $slug;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $text;
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): void
{
$this->title = $title;
}
public function getSlug(): string
{
return $this->slug;
}
public function setSlug(string $slug): void
{
$this->slug = $slug;
}
public function getText(): string
{
return $this->text;
}
public function setText(string $text): void
{
$this->text = $text;
}
}
Be looking at the bundle docs, you should use the TranslatableTrait and not the TranslationTrait for your BlogPost entity.
See the sample here: https://github.com/KnpLabs/DoctrineBehaviors/blob/master/docs/translatable.md
I have a problem about the flush on 2 linked entities (ManyToOne, OneToMany).
I'm on Symfony 5.1.
I just want to persist one "UserSavedCard" with many "UserCartSavedProducts" entities.
But I have an error when I flushed my entities and this error come to this file "in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php (line 3013)"
My function that throw the error :
/**
* Save current user cart in database for later
* #param string|null $title
*/
public function saveCart(?string $title)
{
$cart = $this->getCart();
$cartSaved = new UserCartSaved();
$cartSaved->setUser($this->security->getUser());
$this->em->persist($cartSaved);
foreach ($cart as $item) {
$savedProduct = new UserCartSavedProducts();
$savedProduct->setProduct($item['product']);
$savedProduct->setUserCartSaved($cartSaved);
$this->em->persist($savedProduct);
}
$this->em->flush();
}
When I execute this code above But I have this error :
Notice: Undefined index: 000000007e86ae93000000003f3a2fbb
There is my entites :
UserCartSaved:
<?php
namespace App\Entity;
use App\Repository\UserCartSavedRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\Date;
/**
* #ORM\Entity(repositoryClass=UserCartSavedRepository::class)
*/
class UserCartSaved
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="userCartSaveds")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\OneToMany(targetEntity=UserCartSavedProducts::class, mappedBy="userCartSaved")
*/
private $userCartSavedProducts;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
public function __construct()
{
$this->userCartSavedProducts = new ArrayCollection();
$this->createdAt = new DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* #return Collection|UserCartSavedProducts[]
*/
public function getUserCartSavedProducts(): Collection
{
return $this->userCartSavedProducts;
}
public function addUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if (!$this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts[] = $userCartSavedProduct;
$userCartSavedProduct->setUserCartSaved($this);
}
return $this;
}
public function removeUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if ($this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts->removeElement($userCartSavedProduct);
// set the owning side to null (unless already changed)
if ($userCartSavedProduct->getUserCartSaved() === $this) {
$userCartSavedProduct->setUserCartSaved(null);
}
}
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
UserCartSavedProducts :
<?php
namespace App\Entity;
use App\Repository\UserCartSavedProductsRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCartSavedProductsRepository::class)
*/
class UserCartSavedProducts
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=UserCartSaved::class, inversedBy="userCartSavedProducts")
* #ORM\JoinColumn(nullable=false)
*/
private $userCartSaved;
/**
* #ORM\ManyToOne(targetEntity=Product::class, inversedBy="userCartSavedProducts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $product;
public function getId(): ?int
{
return $this->id;
}
public function getUserCartSaved(): ?UserCartSaved
{
return $this->userCartSaved;
}
public function setUserCartSaved(?UserCartSaved $userCartSaved): self
{
$this->userCartSaved = $userCartSaved;
return $this;
}
public function getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
return $this;
}
}
Product
<?php
namespace App\Entity;
use App\Repository\ProductRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ProductRepository::class)
*/
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity=UserCartSavedProducts::class, mappedBy="product")
*/
private $userCartSavedProducts;
public function __construct()
{
$this->userCartSavedProducts = new ArrayCollection();
}
/**
* #return Collection|UserCartSavedProducts[]
*/
public function getUserCartSavedProducts(): Collection
{
return $this->userCartSavedProducts;
}
public function addUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if (!$this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts[] = $userCartSavedProduct;
$userCartSavedProduct->setProduct($this);
}
return $this;
}
public function removeUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if ($this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts->removeElement($userCartSavedProduct);
// set the owning side to null (unless already changed)
if ($userCartSavedProduct->getProduct() === $this) {
$userCartSavedProduct->setProduct(null);
}
}
return $this;
}
}
I've run into an issue getting the same error, and in my case is that I was storing the entity object into a session and trying to flush it "as is" after retrieval. Regardless I could retrieve and dump the object and everything seemed fine (until flush), I was told that the EM lost management of the contents. So, to get management back, I had to retrieve every single id of every component of the stored object via its own getter, and then via find, retrieve them all and set them again into a new entity instance.
Hello I'm working with sympfony 2,after that i create my database , i wished to create my crud , using command ( generate crud )
but i had this eroor :
[Doctrine\ORM\Mapping\MappingException]
Class "MyApp\SmfBundle\Entity\Client" is not a valid entity or mapped super
class.
My class is
namespace MyApp\SmfBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
*/
class CLient {
/**
* #ORM\GeneratedValue
* #ORM\Id
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string",length=255)
*
*/
private $nom;
/**
* #ORM\Column(type="string",length=255)
*
*/
private $prnom;
/**
* #ORM\Column(type="date")
*
*/
private $DateNaissance;
public function getId() {
return $this->id;
}
public function getNom() {
return $this->nom;
}
public function getPrnom() {
return $this->prnom;
}
public function getDateNaissance() {
return $this->DateNaissance;
}
public function setId($id) {
$this->id = $id;
}
public function setNom($nom) {
$this->nom = $nom;
}
public function setPrnom($prnom) {
$this->prnom = $prnom;
}
public function setDateNaissance($DateNaissance) {
$this->DateNaissance = $DateNaissance;
}
}
WHat i should do, Thank you for your help
class CLient {
PHP is case sensitive. Your class is currently called CLient. Not Client.
I have the One-to-Many bidirectional relationship below.
After generating the crud actions with a symfony2 task, when I try to save the Products associated to a Category in the new/edit Category form, the products are not saved...
namespace Prueba\FrontendBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="category")
*/
class Category
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
/**
* #ORM\Column(name="name")
*/
protected $name;
public function __construct()
{
$this->products = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
public function getProducts()
{
return $this->products;
}
public function setProducts($products)
{
die("fasdf"); //here is not entering
$this->products[] = $products;
}
public function addProduct($product)
{
die("rwerwe"); //here is not entering
$this->products[] = $product;
}
}
namespace Prueba\FrontendBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getCategory()
{
return $this->category;
}
public function setCategory($category)
{
$this->category = $category;
}
public function __toString()
{
return $this->name;
}
}
As its bidirectional you need to update the association on both sides.
Add this function into the Category Entity (you can call it addChild if you like):
public function addProduct($product)
{
$this->children->add($product);
}
And then update both associations at the same time:
public function setProductCategory($product_category)
{
$this->productCategory = $product_category;
$product_category->addProduct($this);
}
Tip: Dont use $children / $parent to describe Entities. Call it what it is $category / $product, you'll run into issues when you want to add in another "parent" relationship.
Another short solution :
in your category entity , add this line to your addProduct function
public function addProduct($product)
{
$product->setCategory($this); // setting the cateogry of product
$this->products[] = $product;
}