Custom query without using doctrine relation - php

I need to create a custom query, without using the doctrine relationship on Symfony 5.4.
I have two entities : Orders and Carrier. This two entities / tables are joined through the column 'id_carrier' (it's the same for both entities). When i execute my query, i get this error:
So i thought to customize the query without passing the association. Can i do this?
I tried also to write the SQL query directly ('SELECT o.* FROM en_orders o INNER JOIN en_carrier c ON c.id_carrier = o.id_carrier), but it not work.
Orders.php
<?php
namespace App\Entity;
use App\Repository\OrdersRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=OrdersRepository::class)
*/
class Orders
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id_order;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $module;
/**
* #ORM\Column(type="string", length=255)
*/
private $payment;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $ps_reference;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $en_reference;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $details;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $invoice;
/**
* #ORM\Column(type="decimal", precision=20, scale=6, nullable=true)
*/
private $total_paid_tax_inclu;
/**
* #ORM\Column(type="decimal", precision=20, scale=6)
*/
private $total_products_wt;
/**
* #ORM\Column(type="decimal", precision=10, scale=0, nullable=true)
*/
private $total_shipping;
/**
* #ORM\Column(type="decimal", precision=10, scale=0, nullable=true)
*/
private $carrier_tax_rate;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $order_note;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date;
/**
* #ORM\OneToMany(targetEntity=App\Entity\Carrier::class, mappedBy="id_carrier")
*/
private $id_carrier;
/**
* #ORM\OneToMany(targetEntity=OrderDetail::class, mappedBy="id_order")
*/
private $orderDetails;
/**
* #ORM\Column(type="integer", nullable=true)
* #ORM\ManyToMany(targetEntity="CartProduct", mappedBy="id_cart")
*/
private $id_cart;
/**
* #ORM\OneToOne(targetEntity=State::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(name="id_state", referencedColumnName="id_state")
*/
private $id_state;
/**
* #ORM\OneToOne(targetEntity=Address::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(name="id_address_delivery", referencedColumnName="id_address")
*/
private $id_address_delivery;
/**
* #ORM\OneToOne(targetEntity=Address::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(name="id_address_invoice", referencedColumnName="id_address")
*/
private $id_address_invoice;
public function __construct()
{
$this->orderDetails = new ArrayCollection();
}
public function getIdOrder(): ?int
{
return $this->id_order;
}
public function getModule(): ?string
{
return $this->module;
}
public function setModule(?string $module): self
{
$this->module = $module;
return $this;
}
public function getPayment(): ?string
{
return $this->payment;
}
public function setPayment(string $payment): self
{
$this->payment = $payment;
return $this;
}
public function getPsReference(): ?string
{
return $this->ps_reference;
}
public function setPsReference(?string $ps_reference): self
{
$this->ps_reference = $ps_reference;
return $this;
}
public function getEnReference(): ?string
{
return $this->en_reference;
}
public function setEnReference(?string $en_reference): self
{
$this->en_reference = $en_reference;
return $this;
}
public function getDetails(): ?string
{
return $this->details;
}
public function setDetails(?string $details): self
{
$this->details = $details;
return $this;
}
public function getInvoice(): ?int
{
return $this->invoice;
}
public function setInvoice(?int $invoice): self
{
$this->invoice = $invoice;
return $this;
}
public function getTotalPaidTaxInclu(): ?string
{
return $this->total_paid_tax_inclu;
}
public function setTotalPaidTaxInclu(?string $total_paid_tax_inclu): self
{
$this->total_paid_tax_inclu = $total_paid_tax_inclu;
return $this;
}
public function getTotalProductsWt(): ?string
{
return $this->total_products_wt;
}
public function setTotalProductsWt(string $total_products_wt): self
{
$this->total_products_wt = $total_products_wt;
return $this;
}
public function getTotalShipping(): ?string
{
return $this->total_shipping;
}
public function setTotalShipping(?string $total_shipping): self
{
$this->total_shipping = $total_shipping;
return $this;
}
public function getCarrierTaxRate(): ?string
{
return $this->carrier_tax_rate;
}
public function setCarrierTaxRate(?string $carrier_tax_rate): self
{
$this->carrier_tax_rate = $carrier_tax_rate;
return $this;
}
public function getOrderNote(): ?string
{
return $this->order_note;
}
public function setOrderNote(?string $order_note): self
{
$this->order_note = $order_note;
return $this;
}
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(?\DateTimeInterface $date): self
{
$this->date = $date;
return $this;
}
public function getIdCarrier(): ?OrderCarrier
{
return $this->id_carrier;
}
public function setIdCarrier(?OrderCarrier $id_carrier): self
{
// unset the owning side of the relation if necessary
if ($id_carrier === null && $this->id_carrier !== null) {
$this->id_carrier->setIdOrder(null);
}
// set the owning side of the relation if necessary
if ($id_carrier !== null && $id_carrier->getIdOrder() !== $this) {
$id_carrier->setIdOrder($this);
}
$this->id_carrier = $id_carrier;
return $this;
}
/**
* #return Collection<int, OrderDetail>
*/
public function getOrderDetails(): Collection
{
return $this->orderDetails;
}
public function addOrderDetail(OrderDetail $orderDetail): self
{
if (!$this->orderDetails->contains($orderDetail)) {
$this->orderDetails[] = $orderDetail;
$orderDetail->setIdOrder($this);
}
return $this;
}
public function removeOrderDetail(OrderDetail $orderDetail): self
{
if ($this->orderDetails->removeElement($orderDetail)) {
// set the owning side to null (unless already changed)
if ($orderDetail->getIdOrder() === $this) {
$orderDetail->setIdOrder(null);
}
}
return $this;
}
public function getIdCart(): ?int
{
return $this->id_cart;
}
public function setIdCart(?int $id_cart): self
{
$this->id_cart = $id_cart;
return $this;
}
public function getIdState(): ?State
{
return $this->id_state;
}
public function setIdState(?State $id_state): self
{
$this->id_state = $id_state;
return $this;
}
public function getIdAddreddDelivery(): ?Address
{
return $this->id_address_delivery;
}
public function setIdAddreddDelivery(?Address $id_address_delivery): self
{
$this->id_address_delivery = $id_address_delivery;
return $this;
}
public function getIdAddressInvoice(): ?Address
{
return $this->id_address_invoice;
}
public function setIdAddressInvoice(?Address $id_address_invoice): self
{
$this->id_address_invoice = $id_address_invoice;
return $this;
}
}
Carrier.php
<?php
namespace App\Entity;
use App\Repository\CarrierRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="en_carrier")
* #ORM\Entity(repositoryClass=CarrierRepository::class)
*/
class Carrier
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity=App\Entity\Orders::class, inversedBy="id_carrier")
* #ORM\JoinColumn(name="id_carrier", referencedColumnName="id_carrier")
*/
private $id_carrier;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $name;
public function getIdCarrier(): ?int
{
return $this->id_carrier;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
}
OrdersRepository.php
/**
* #return Orders[] Returns an array of Orders objects
*/
public function getFilteredOrders(): array
{
return $this->createQueryBuilder('o')
->select('o')
->innerJoin('o.en_carrier','c','WITH','o.id_carrier = c.id_carrier')
->getQuery()
->getResult()
;
}

Try :
return $this->createQueryBuilder('o')
->select('o, c')
->innerJoin('o.id_carrier', 'c')
->getQuery()
->getResult()
;
If you really want to make a query without the QueryBuilder, you can use DQL, but it is not recommanded (for example, to be safe with SQL injections). You can have more informations here :
https://www.doctrine-project.org/projects/doctrine-orm/en/2.11/reference/dql-doctrine-query-language.html

Related

DQL Queries not functionning (Doctrine2; Symfony5.0)

I'm having trouble with DQL queries on a project I'm working on. What the DQL is supposed to do is find in the DB all the datas that are related to a productLine variable; that a user would type and search for into a form.
My issue is when I run a test with a product Line; I get an "Error 500" thrown; and I know the error origins from the Repository file; since the controller works fine (I've added some var_dumps in the controller after the query's line to check and I'm not reaching it when testing with the faulty function, whereas with another working function I can reach it).
I know that the data typed in by the user is collected (the product Line entered by the user), there seems to be an issue with DQL processing the query that I can't seem to find an answer for anywhere.
Without further ado; here's the code.
Working fine query
public function findByLotNumber($lotNumber){
return $this->createQueryBuilder('u')
->distinct()
->where('u.lotNumber LIKE :lotNumberS')
->setParameter('lotNumberS', $lotNumber . '%')
->getQuery()
->getResult();
}
faulty query
public function findByCriteriaIdentification($criteriaIdentification){
$givenLotNumber = $_POST['lotNumber'];
if(empty($_POST['lotNumber'])){
$givenLotNumber = '%';
}
$givenProductLine = $_POST['productLine'];
if(empty($_POST['productLine'])){
$givenProductLine = '%';
}
$varTest = $this->createQueryBuilder('u')
->distinct()
->where('u.lotNumber LIKE :lotNumberS')
->orWhere('u.productLine LIKE :productLineS')
->setParameter('lotNumberS', $givenLotNumber)
->setParameter('productLineS', $givenProductLine);
$queryTest = $varTest->getQuery();
return $queryTest->execute();
}
Does anyone have an insight regarding what I'm coding wrong ?
PS: this being a corporate project I don't have the possibility of upgrading to Symfo 6 or Doctrine3 at the moment.
EDIT: Here's the class of the entity i'm querying:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\WafRepository")
*/
class Waf extends Sil
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="App\Entity\Sil")
*/
private $id;
/**
* #ORM\Column(type="integer")
*/
private $rankId;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $size;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $thickness;
/*public function getId(): ?int
{
return $this->id;
}*/
public function getRankId(): ?int
{
return $this->rankId;
}
public function setRankId(int $rankId): self
{
$this->rankId = $rankId;
return $this;
}
public function getSize(): ?int
{
return $this->size;
}
public function setSize(int $size): self
{
$this->size = $size;
return $this;
}
public function getThickness(): ?int
{
return $this->thickness;
}
public function setThickness(?int $thickness): self
{
$this->thickness = $thickness;
return $this;
}
}
In case its useful, I'm adding as well the class "sili" that waf is an extent from:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SiliconRepository")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="silType", type="string")
*/
class Sil
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=20)
*/
private $lotNumber;
/**
* #ORM\Column(type="string", length=80, nullable=true)
*/
private $productLine;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $productCode;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $productLineCode;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $sourceLot;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $division;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
//private $comment;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $testStatus;
/**
* #ORM\Column(type="integer", nullable=true)
*/
//private $lastUpdate;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $maturity;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Operations", mappedBy="silicon")
*/
private $operations;
/**
* #ORM\OneToMany(targetEntity="App\Entity\State", mappedBy="silicon")
*/
private $states;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $fatherLotNumber;
public function __construct()
{
$this->operations = new ArrayCollection();
$this->states = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLotNumber(): ?string
{
return $this->lotNumber;
}
public function setLotNumber(string $lotNumber): self
{
$this->lotNumber = $lotNumber;
return $this;
}
public function getProductLine(): ?string
{
return $this->productLine;
}
public function setProductLine(?string $productLine): self
{
$this->productLine = $productLine;
return $this;
}
public function getProductCode(): ?string
{
return $this->productCode;
}
public function setProductCode(?string $productCode): self
{
$this->productCode = $productCode;
return $this;
}
public function getProductLineCode(): ?string
{
return $this->productLineCode;
}
public function setProductLineCode(?string $productLineCode): self
{
$this->productLineCode = $productLineCode;
return $this;
}
public function getSourceLot(): ?string
{
return $this->sourceLot;
}
public function setSourceLot(?string $sourceLot): self
{
$this->sourceLot = $sourceLot;
return $this;
}
public function getDivision(): ?int
{
return $this->division;
}
public function setDivision(?int $division): self
{
$this->division = $division;
return $this;
}
/*public function getComment(): ?string
{
return $this->comment;
}
public function setComment(?string $comment): self
{
$this->comment = $comment;
return $this;
}*/
public function getTestStatus(): ?string
{
return $this->testStatus;
}
public function setTestStatus(?string $testStatus): self
{
$this->testStatus = $testStatus;
return $this;
}
/*public function getLastUpdate(): ?int
{
return $this->lastUpdate;
}
public function setLastUpdate(int $lastUpdate): self
{
$this->lastUpdate = $lastUpdate;
return $this;
}*/
public function getMaturity(): ?int
{
return $this->maturity;
}
public function setMaturity(?int $maturity): self
{
$this->maturity = $maturity;
return $this;
}
/**
* #return Collection|Operations[]
*/
public function getOperations(): Collection
{
return $this->operations;
}
public function addOperation(Operations $operation): self
{
while (!($this)->operations->contains($operation)) {
$this->operations[] = $operation;
$operation->setSilicon($this);
}
return $this;
}
public function removeOperation(Operations $operation): self
{
if ($this->operations->contains($operation)) {
$this->operations->removeElement($operation);
//$this->reformatTab($this->operations);
// set the owning side to null (unless already changed)
if ($operation->getSilicon() === $this) {
$operation->setSilicon(null);
}
}
return $this;
}
/**
* #return Collection|State[]
*/
public function getStates(): Collection
{
return $this->states;
}
public function addState(State $state): self
{
if (!$this->states->contains($state)) {
$this->states[] = $state;
$state->setSilicon($this);
}
return $this;
}
public function removeState(State $state): self
{
if ($this->states->contains($state)) {
$this->states->removeElement($state);
// set the owning side to null (unless already changed)
if ($state->getSilicon() === $this) {
$state->setSilicon(null);
}
}
return $this;
}
public function getFatherLotNumber(): ?string
{
return $this->fatherLotNumber;
}
public function setFatherLotNumber(?string $fatherLotNumber): self
{
$this->fatherLotNumber = $fatherLotNumber;
return $this;
}
}
Thanks in advance !

getChildren(): Return value must be of type Doctrine\Common\Collections\Collection, string returned

In my code, I have implemented OneToMany self-referencing relationship. I have initialized array collection in the constructor. When I send a query parent is added to the children. But when I try to return an object in the children or parent property I get not an Object but an Array collection string. The error looks like this:
App\Entity\Employee::getChildren(): Return value must be of type
Doctrine\Common\Collections\Collection, string returned
Here is my entity:
<?php
namespace App\Entity;
use App\Repository\EmployeeRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=EmployeeRepository::class)
*/
class Employee
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $parent_id;
/**
* #ORM\Column(type="string", length=30)
*/
private $firstName;
/**
* #ORM\Column(type="string", length=30)
*/
private $lastName;
/**
* #ORM\Column(type="string", length=40)
*/
private $position;
/**
* #ORM\Column(type="string", length=20)
*/
private $phoneNumber;
/**
* #ORM\Column(type="string", length=255)
*/
private $email;
/**
* #ORM\Column(type="integer")
*/
private $workExperience;
/**
* #ORM\Column(type="integer")
*/
private $levelOfKnowledge;
/**
* #ORM\Column(nullable=true)
* #ORM\OneToMany(targetEntity=Employee::class, mappedBy="parent")
*/
private $children;
/**
* #ORM\Column(nullable=true)
* #ORM\ManyToOne(targetEntity=Employee::class, inversedBy="children")
*/
private $parent;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getPosition(): ?string
{
return $this->position;
}
public function setPosition(string $position): self
{
$this->position = $position;
return $this;
}
public function getPhoneNumber(): ?string
{
return $this->phoneNumber;
}
public function setPhoneNumber(string $phoneNumber): self
{
$this->phoneNumber = $phoneNumber;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getWorkExperience(): ?int
{
return $this->workExperience;
}
public function setWorkExperience(int $workExperience): self
{
$this->workExperience = $workExperience;
return $this;
}
public function getLevelOfKnowledge(): ?int
{
return $this->levelOfKnowledge;
}
public function setLevelOfKnowledge(int $levelOfKnowledge): self
{
$this->levelOfKnowledge = $levelOfKnowledge;
return $this;
}
public function getParent(): ?self
{
return $this->parent;
}
public function setParent(Employee $employee): void
{
$this->parent = $employee;
}
/**
* #return Collection|Employee[]|null
*/
public function getChildren(): Collection
{
dump($this->children);
return $this->children;
}
public function __toString(): string
{
return $this->children;
}
/**
* #return mixed
*/
public function getParentId()
{
return $this->parent_id;
}
/**
* #param mixed $parent_id
*/
public function setParentId($parent_id): void
{
$this->parent_id = $parent_id;
}
}
The problem lies in this part:
/**
* #ORM\Column(nullable=true)
* #ORM\OneToMany(targetEntity=Employee::class, mappedBy="parent")
*/
private $children;
as you've mapped your field both as a column and a relation. You must not use #Column along with #OneToMany as it's not even making sens - the children is not reflected in the database anyway.

Symfony: $images must be an instance of Doctrine\Common\Collections\ArrayCollection, Doctrine\ORM\PersistentCollection used

I currently have the following error with my entity code, and I don't really understand why I am having this problem.
I only have it in the page of my create dashboard, while I don't call the images but only the heritages, and in the form everything works fine.
I have tried changing Collection to ArrayCollection but nothing has changed.
<?php
namespace App\Entity;
use App\Repository\PatrimoineRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass=PatrimoineRepository::class)
*/
class Patrimoine
{
/**
* #ORM\Id
* #ORM\Column(type="string", unique=true)
* #ORM\GeneratedValue("UUID")
*/
private ?string $id = null;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $name;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $description;
/**
* #ORM\Column(type="json")
* #Assert\Collection(
* fields={
* "lat" = {
* #Assert\NotBlank,
* #Assert\Regex("/^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/")
* },
* "lng" = {
* #Assert\NotBlank,
* #Assert\Regex("/^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/")
* },
* },
* missingFieldsMessage="Le champs {{ field }} est manquant"
* )
*/
private array $localisation = [];
/**
* #ORM\Column(type="datetime_immutable")
*/
private ?\DateTimeImmutable $created_at;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $statut;
/**
* #ORM\ManyToOne(targetEntity=CategoryPatrimoine::class, inversedBy="patrimoines")
* #ORM\JoinColumn(nullable=false)
*/
private ?CategoryPatrimoine $category;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $visibility;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="patrimoines")
* #ORM\JoinColumn(nullable=false)
*/
private ?User $author;
/**
* #ORM\OneToMany(targetEntity=Image::class, mappedBy="patrimoine", orphanRemoval=true)
*/
private ArrayCollection $images;
public function __construct()
{
$this->setCreatedAt(new \DateTimeImmutable());
$this->images = new ArrayCollection();
}
public function getId(): ?string
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getLocalisation(): ?array
{
return $this->localisation;
}
public function setLocalisation(array $localisation): self
{
$this->localisation = $localisation;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeImmutable $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getStatut(): ?string
{
return $this->statut;
}
public function setStatut(string $statut): self
{
$this->statut = $statut;
return $this;
}
public function getCategory(): ?CategoryPatrimoine
{
return $this->category;
}
public function setCategory(?CategoryPatrimoine $category): self
{
$this->category = $category;
return $this;
}
public function getVisibility(): ?string
{
return $this->visibility;
}
public function setVisibility(string $visibility): self
{
$this->visibility = $visibility;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
/**
* #return Collection|Image[]
*/
public function getImages(): Collection
{
return $this->images;
}
public function addImage(Image $image): self
{
if (!$this->images->contains($image)) {
$this->images[] = $image;
$image->setPatrimoine($this);
}
return $this;
}
public function removeImage(Image $image): self
{
// set the owning side to null (unless already changed)
if ($this->images->removeElement($image) && $image->getPatrimoine() === $this) {
$image->setPatrimoine(null);
}
return $this;
}
}
I faced a similar problem too. You must declare the property as Collection (interface), not as implementation ArrayCollection because Doctrine ORM uses PersistentCollection when picks up data from database but you declare the property as ArrayCollection, and type mismatch happens.
class SomeEntity {
private Collection $items;
// all other code
}
I just realized that the typing of $ images was wrong, it was "ArrayCollection" whereas it must be "Collection"

SQLSTATE[42S22]: Column not found: 1054 Champ 't0.id' inconnu dans where clause ( Symfony 5 , API Platform )

I have 2 classes , Class Child "Livreur" inherite from Class Parent "Users" .
Problem in return data after insert by API Plateform . (it inserted by success but data deosn't returned + doesn't insert in table Users, before that it inserted in Users+Livreur but now no ).
Class "Users" (parent) :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UsersRepository;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping ;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass=UsersRepository::class)
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* collectionOperations={"post"={},"get"={}},
* itemOperations={"get","put"={"denormalization_Context"={"groups"={"put"}}}}
* )
*/
class Users implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180)
* #Groups({"read"})
*/
private $email;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255)
* #Groups({"read"})
* #Groups({"put"})
*/
private $password;
/**
* #Assert\NotBlank()
* #Assert\Expression("this.getPassword() == this.getRepassword()",message="Mot de pass doit etre le meme dans les 2 deux champs")
*/
private $repassword;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=30)
* #Groups({"read"})
* #Groups({"put"})
*/
private $username;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text")
* #Groups({"read"})
* #Groups({"put"})
*/
private $roles;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $cin;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $nom;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $prenom;
/**
* #Assert\NotBlank()
* #ORM\Column(type="date")
* #Groups({"read"})
*/
private $dtn;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
*/
private $dtype;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
*/
private $img;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=30, nullable=true)
* #Groups({"read"})
* #Groups({"put"})
*/
private $rib;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
* #Groups({"put"})
*/
private $adresse;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
* #Groups({"put"})
*/
private $tel;
protected function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getRoles(): array
{
return array('ROLE_USER');
}
public function setRoles(string $roles): self
{
$this->roles = $roles;
return $this;
}
public function getCin(): ?string
{
return $this->cin;
}
public function setCin(string $cin): self
{
$this->cin = $cin;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getDtn(): ?\DateTimeInterface
{
return $this->dtn;
}
public function setDtn(\DateTimeInterface $dtn): self
{
$this->dtn = $dtn;
return $this;
}
public function getDtype(): ?string
{
return $this->dtype;
}
public function setDtype(?string $dtype): self
{
$this->dtype = $dtype;
return $this;
}
public function getImg(): ?string
{
return $this->img;
}
public function setImg(?string $img): self
{
$this->img = $img;
return $this;
}
public function getRib(): ?string
{
return $this->rib;
}
public function setRib(?string $rib): self
{
$this->rib = $rib;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(?string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getTel(): ?string
{
return $this->tel;
}
public function setTel(string $tel): self
{
$this->tel = $tel;
return $this;
}
public function getSalt()
{
// TODO: Implement getSalt() method.
}
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
public function getRepassword()
{
return $this->repassword;
}
public function setRepassword($repassword): void
{
$this->repassword = $repassword;
}
}
Class Livreur (child) :
<?php
namespace App\Entity;
use App\Repository\LivreurRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;
/**
* #ORM\Entity(repositoryClass=LivreurRepository::class)
* #ApiResource()
*/
class Livreur extends Users
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=20)
*/
private $type_vehicule;
/**
* #ORM\Column(type="string", length=20)
*/
private $permis;
/**
* #ORM\Column(type="boolean")
*/
private $disponibilite;
/**
* #ORM\Column(type="float")
*/
private $coffre;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $log;
/**
* #ORM\OneToMany(targetEntity=Commande::class, mappedBy="livreur")
*/
private $commandes;
/**
* #ORM\OneToMany(targetEntity=Conge::class, mappedBy="livreur")
*/
private $conges;
/**
* #ORM\ManyToOne(targetEntity=Agence::class, inversedBy="livreurs")
* #ORM\JoinColumn(nullable=false)
*/
private $agence;
/**
* #ORM\OneToOne(targetEntity=SalaireEmp::class, inversedBy="livreur", cascade={"persist", "remove"})
*/
private $salaire_emp;
/**
* #ORM\ManyToOne(targetEntity=Ville::class, inversedBy="livreurs")
* #ORM\JoinColumn(nullable=false)
*/
private $ville;
public function __construct()
{
$this->commandes = new ArrayCollection();
$this->conges = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTypeVehicule(): ?string
{
return $this->type_vehicule;
}
public function setTypeVehicule(string $type_vehicule): self
{
$this->type_vehicule = $type_vehicule;
return $this;
}
public function getPermis(): ?string
{
return $this->permis;
}
public function setPermis(string $permis): self
{
$this->permis = $permis;
return $this;
}
public function getDisponibilite(): ?int
{
return $this->disponibilite;
}
public function setDisponibilite(int $disponibilite): self
{
$this->disponibilite = $disponibilite;
return $this;
}
public function getCoffre(): ?float
{
return $this->coffre;
}
public function setCoffre(float $coffre): self
{
$this->coffre = $coffre;
return $this;
}
public function getLog(): ?string
{
return $this->log;
}
public function setLog(?string $log): self
{
$this->log = $log;
return $this;
}
/**
* #return Collection|Commande[]
*/
public function getCommandes(): Collection
{
return $this->commandes;
}
public function addCommande(Commande $commande): self
{
if (!$this->commandes->contains($commande)) {
$this->commandes[] = $commande;
$commande->setLivreur($this);
}
return $this;
}
public function removeCommande(Commande $commande): self
{
if ($this->commandes->removeElement($commande)) {
// set the owning side to null (unless already changed)
if ($commande->getLivreur() === $this) {
$commande->setLivreur(null);
}
}
return $this;
}
/**
* #return Collection|Conge[]
*/
public function getConges(): Collection
{
return $this->conges;
}
public function addConge(Conge $conge): self
{
if (!$this->conges->contains($conge)) {
$this->conges[] = $conge;
$conge->setLivreur($this);
}
return $this;
}
public function removeConge(Conge $conge): self
{
if ($this->conges->removeElement($conge)) {
// set the owning side to null (unless already changed)
if ($conge->getLivreur() === $this) {
$conge->setLivreur(null);
}
}
return $this;
}
public function getAgence(): ?Agence
{
return $this->agence;
}
public function setAgence(?Agence $agence): self
{
$this->agence = $agence;
return $this;
}
public function getSalaireEmp(): ?SalaireEmp
{
return $this->salaire_emp;
}
public function setSalaireEmp(?SalaireEmp $salaire_emp): self
{
$this->salaire_emp = $salaire_emp;
return $this;
}
public function getVille(): ?Ville
{
return $this->ville;
}
public function setVille(?Ville $ville): self
{
$this->ville = $ville;
return $this;
}
}
Looks like you forgot to set an inheritance mapping strategy. Here is an example:
// (..)
/**
* #ORM\Entity(repositoryClass=UsersRepository::class)
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"users" = "Users", "livreur" = "Livreur"})
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* collectionOperations={"post"={},"get"={}},
* itemOperations={"get","put"={"denormalization_Context"={"groups"={"put"}}}}
* )
*/
class Users implements UserInterface
{
// (..)
This will add an extra field "discr" to the tables of both your classes so you will have to update their table configurations, for example with:
bin/console doctrine:schema:update --force
or if you use migrations:
bin/console doctrine:migrations:diff
bin/console doctrine:migrations:migrate
For explanation of Mapping Strategies and their alternatives see the Inheritance Mapping page on doctrine-project.org

The entity-class mapping is invalid

I am having trouble in debugging mapping error of Entity.
When I run php bin/console doctrine:schema:validate, It shows the error , which is as follow
[FAIL] The entity-class App\Entity\Company mapping is invalid:
The association App\Entity\Company#policies refers to the owning side field App\Entity\Policy#company_id which does not exist.
I tried this post ( Entity class mapping is invalid) which is pretty much same with me but seems like not working.
This is my Company Entity
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
*/
class Company
{
use TimestampableEntity;
const STATUS_ACTIVE = "ACTIVE";
const STATUS_STAGING = "STAGING";
const STATUS_INACTIVE = "INACTIVE";
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $address;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $email;
/**
* #ORM\Column(type="string", length=255)
*/
private $status;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $logo;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Policy", mappedBy="company_id")
*/
private $policies;
/**
* #ORM\Column(type="string", length=255)
*/
private $url;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="companies")
*/
private $user;
public function __construct()
{
$this->policies = 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;
}
public function getAddress(): ?string
{
return $this->address;
}
public function setAddress(string $address): self
{
$this->address = $address;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getLogo(): ?string
{
return $this->logo;
}
public function setLogo(string $logo): self
{
$this->logo = $logo;
return $this;
}
/**
* #return Collection|Policy[]
*/
public function getPolicies(): Collection
{
return $this->policies;
}
public function addPolicy(Policy $policy): self
{
if (!$this->policies->contains($policy)) {
$this->policies[] = $policy;
$policy->setCompany($this);
}
return $this;
}
public function removePolicy(Policy $policy): self
{
if ($this->policies->contains($policy)) {
$this->policies->removeElement($policy);
// set the owning side to null (unless already changed)
if ( $policy->getCompany() === $this) {
$policy->setCompany(null);
}
}
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
}
And this is my Policy Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\PolicyRepository")
*/
class Policy
{
use TimestampableEntity;
const VEH_TYPE_MINIBUS = "Minibus";
const VEH_TYPE_FOUR_WHEEL = "4x4";
const VEH_TYPE_CAR = "Car";
const VEH_PURPOSE_PERSONAL = "Personal";
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $ref_id;
/**
* #ORM\Column(type="string", length=255)
*/
private $policy_code;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Company")
* #ORM\JoinColumn(name="company_id", nullable=false, referencedColumnName="id")
*/
private $company;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $status;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank
*/
private $fromDate;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank
*/
private $toDate;
/**
* #ORM\Column(type="string", length=255)
*/
private $vehicle_type;
/**
* #ORM\Column(type="string", length=255)
*/
private $purpose;
/**
* #ORM\Column(type="float",scale=2)
*/
private $total_amt;
/**
* #ORM\Column(type="float", scale=2)
*/
private $cover_amt;
/**
* #ORM\Column(type="float", scale=2)
*/
private $discount;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Customer", inversedBy="policies")
*/
private $customer;
public function getId(): ?int
{
return $this->id;
}
public function getRefId(): ?string
{
return $this->ref_id;
}
public function setRefId(string $ref_id): self
{
$this->ref_id = $ref_id;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getFromDate(): ?\DateTimeInterface
{
return $this->fromDate;
}
public function setFromDate(\DateTimeInterface $fromDate): self
{
$this->fromDate = $fromDate;
return $this;
}
public function getToDate(): ?\DateTimeInterface
{
return $this->toDate;
}
public function setToDate(\DateTimeInterface $toDate): self
{
$this->toDate = $toDate;
return $this;
}
public function getTotalAmt(): ?float
{
return $this->total_amt;
}
public function setTotalAmt(float $total_amt): self
{
$this->total_amt = $total_amt;
return $this;
}
public function getCoverAmt(): ?float
{
return $this->cover_amt;
}
public function setCoverAmt(float $cover_amt): self
{
$this->cover_amt = $cover_amt;
return $this;
}
public function getCompany(): ?Company
{
return $this->company;
}
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
public function getCustomer(): ?Customer
{
return $this->customer;
}
public function setCustomer(?Customer $customer): self
{
$this->customer = $customer;
return $this;
}
public function getVehicleType(): ?string
{
return $this->vehicle_type;
}
public function setVehicleType(string $vehicle_type): self
{
$this->vehicle_type = $vehicle_type;
return $this;
}
public function getPurpose(): ?string
{
return $this->purpose;
}
public function setPurpose(string $purpose): self
{
$this->purpose = $purpose;
return $this;
}
public function getDiscount(): ?float
{
return $this->discount;
}
public function setDiscount(float $discount): self
{
$this->discount = $discount;
return $this;
}
public function getPolicyCode(): ?string
{
return $this->policy_code;
}
public function setPolicyCode(string $policy_code): self
{
$this->policy_code = $policy_code;
return $this;
}
}
company_id does not exist in the entity only in the table. So try mappedBy="company instead? Hope it helps!

Categories