Doctrine entity always saves null on persist even when set - php

I'm trying to persist some data to the database but even though I'm setting a field it sets it to null when the actual SQL runs. The field is set to not null in the database which throws an error.
My code:
$db_order = new Orders;
$db_order->setDateCreated(new \DateTime());
$db_order->setLastUpdated(null);
$db_order->setDateAssigned(null);
$db_order->setCreatedBy($user->getId());
$db_order->setAttachmentId($order->getFaxId());
$db_order->setPatientId($order->getPatientId());
$db_order->setPaymentType($order->getPaymentType());
$db_order->setInsuranceName($order->getInsuranceName());
$db_order->setInsuranceNo($order->getInsuranceNo());
$db_order->setCash($order->getCash());
$db_order->setPrimaryClientId($order->getPrimaryClient());
$db_order->setSecondaryClients($secondaryClients);
$db_order->setEmployees($employees);
$db_order->setDates($dates);
$db_order->setNotes($note);
dump($db_order->getPatientId());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($db_order);
$entityManager->flush();
I was double checking with that dump before the persist and it has the field set correctly. Yet when the page runs...
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'patient_id' cannot be null
I don't understand how it could be null? Any ideas?
Orders Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
/**
* #ORM\Entity(repositoryClass="App\Repository\OrdersRepository")
* #Assert\GroupSequenceProvider()
*/
class Orders implements GroupSequenceProviderInterface
{
const TYPE_InsuranceOnly = 1;
const TYPE_InsuranceAndCash = 2;
const TYPE_CashOnly = 3;
/**
* #ORM\ManyToOne(targetEntity="Patients")
* #ORM\JoinColumn(name="patient_id", referencedColumnName="id")
*/
private $patients;
/**
* #ORM\ManyToOne(targetEntity="Clients")
* #ORM\JoinColumn(name="primary_client_id", referencedColumnName="id")
*/
private $primaryClient;
public function __construct()
{
}
public function getPatients(): Patients
{
return $this->patients;
}
public function getPrimaryClient(): Clients
{
return $this->primaryClient;
}
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $date_created;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_updated;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date_assigned;
/**
* #ORM\Column(type="smallint")
* #ORM\OneToOne(targetEntity="Employee")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
*/
private $created_by;
/**
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="Attachments")
* #ORM\JoinColumn(name="attachment_id", referencedColumnName="id")
*/
private $attachment_id;
/**
* #ORM\Column(type="integer", nullable=false)
*/
private $patient_id;
/**
* #ORM\Column(type="smallint")
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $payment_type;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance Name field cannot be blank")
*/
private $insurance_name;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance # field cannot be blank")
*/
private $insurance_no;
/**
* #ORM\Column(type="decimal", precision=15, scale=2, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $cash;
/**
* #ORM\Column(name="primary_client_id", type="integer")
*/
private $primaryClientId;
/**
* One Order has Many Secondary Clients.
* #ORM\ManyToMany(targetEntity="Clients")
* #ORM\JoinTable(name="orders_secondary_clients",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="client_id", referencedColumnName="id")}
* )
*/
private $secondaryClients;
/**
* One Order has Many Employees.
* #ORM\ManyToMany(targetEntity="Employee")
* #ORM\JoinTable(name="orders_employees",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="employee_id", referencedColumnName="id")},
* )
*/
private $employees;
/**
* #ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
*/
private $dates;
/**
* #ORM\Column(type="text", length=100000, nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="smallint")
*/
private $status = 0;
public function getId(): ?int
{
return $this->id;
}
public function getDateAssigned(): ?\DateTimeInterface
{
return $this->date_assigned;
}
public function setDateAssigned(?\DateTimeInterface $date_assigned): self
{
$this->date_assigned = $date_assigned;
return $this;
}
public function getCreatedBy(): ?int
{
return $this->created_by;
}
public function setCreatedBy(int $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getDateCreated(): \DateTimeInterface
{
return $this->date_created;
}
public function setDateCreated(\DateTimeInterface $dateCreated): self
{
$this->date_created = $dateCreated;
return $this;
}
public function getLastUpdated(): ?\DateTimeInterface
{
return $this->last_updated;
}
public function setLastUpdated(?\DateTimeInterface $last_updated): self
{
$this->last_updated = $last_updated;
return $this;
}
public function getPatientId(): ?int
{
return $this->patient_id;
}
public function setPatientId(int $patient_id): self
{
$this->patient_id = $patient_id;
return $this;
}
public function getPaymentType(): ?int
{
return $this->payment_type;
}
public function setPaymentType(int $payment_type): self
{
$this->payment_type = $payment_type;
return $this;
}
public function getInsuranceName(): ?string
{
return $this->insurance_name;
}
public function setInsuranceName(?string $insurance_name): self
{
$this->insurance_name = $insurance_name;
return $this;
}
public function getInsuranceNo(): ?string
{
return $this->insurance_no;
}
public function setInsuranceNo(?string $insurance_no): self
{
$this->insurance_no = $insurance_no;
return $this;
}
public function getCash() : float
{
return $this->cash;
}
public function setCash(float $cash): self
{
$this->cash = $cash;
return $this;
}
public function getAttachmentId(): ?int
{
return $this->attachment_id;
}
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getPrimaryClientId(): int
{
return $this->primaryClientId;
}
public function setPrimaryClientId(int $client): self
{
$this->primaryClientId = $client;
return $this;
}
public function getSecondaryClients() : ?PersistentCollection
{
return $this->secondaryClients;
}
public function setSecondaryClients(?array $clients): self
{
$this->secondaryClients = $clients;
return $this;
}
public function getEmployees() : PersistentCollection
{
return $this->employees;
}
public function setEmployees(array $employees): self
{
$this->employees = $employees;
return $this;
}
public function getDates() : PersistentCollection
{
return $this->dates;
}
public function addDate(\DateTime $date): self
{
$orderDate = new OrderDates();
$orderDate->setDate($date);
$orderDate->setOrder($this);
$this->dates[] = $orderDate;
return $this;
}
public function setDates(array $dates): self
{
foreach($dates as $date)
{
$this->addDate(new \DateTime($date));
}
return $this;
}
public function getNotes() : ?string
{
return $this->notes;
}
public function setNotes(?string $notes): self
{
$this->notes = $notes;
return $this;
}
public function getStatus() : int
{
return $this->status;
}
public function setStatus(int $status): self
{
$this->notes = $status;
return $this;
}
public function getGroupSequence()
{
$group = null;
switch($this->payment_type) {
case self::TYPE_InsuranceOnly:
$group = 'insuranceOnly';
break;
case self::TYPE_InsuranceAndCash:
$group = 'insuranceAndCash';
break;
case self::TYPE_CashOnly:
$group = 'cashOnly';
break;
}
return [
[
'Orders',
$group
]
];
}
}
EDIT:
I decided to just run the SQL statement output by the persist against the DB and it seems not only was the patient missing but also the primary_client_id field. I now assume it has something to do with the associations I have in there for patients and primaryclient since those are the two fields that are missing. I'm not sure what would be wrong there though.

For the sake of posterity, after the discussion in the post comments this is the end result of my entity. It now saves the id's in the table, there was no need for a separate field JUST to save the int. The only big difference is I need to lookup the patient and primary Client to pass in, instead of just passing the id value (integer).
Code:
$patient = $this->getDoctrine()
->getRepository(Patients::class)
->find($order->getPatientId());
$primaryClient = $this->getDoctrine()
->getRepository(Clients::class)
->findOneById($order->getPrimaryClient());
$db_order = new Orders();
$db_order->setDateCreated(new \DateTime());
$db_order->setLastUpdated(null);
$db_order->setDateAssigned(null);
$db_order->setCreatedBy($user->getId());
$db_order->setAttachmentId($order->getFaxId());
$db_order->setPatient($patient);
$db_order->setPaymentType($order->getPaymentType());
$db_order->setInsuranceName($order->getInsuranceName());
$db_order->setInsuranceNo($order->getInsuranceNo());
$db_order->setCash($order->getCash());
$db_order->setPrimaryClient($primaryClient);
$db_order->setSecondaryClients($secondaryClients);
$db_order->setEmployees($employees);
$db_order->setDates($dates);
$db_order->setNotes($note);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($db_order);
$entityManager->flush();
Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
/**
* #ORM\Entity(repositoryClass="App\Repository\OrdersRepository")
* #Assert\GroupSequenceProvider()
*/
class Orders implements GroupSequenceProviderInterface
{
const TYPE_InsuranceOnly = 1;
const TYPE_InsuranceAndCash = 2;
const TYPE_CashOnly = 3;
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $date_created;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_updated;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date_assigned;
/**
* #ORM\Column(type="smallint")
* #ORM\OneToOne(targetEntity="Employee")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
*/
private $created_by;
/**
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="Attachments")
* #ORM\JoinColumn(name="attachment_id", referencedColumnName="id")
*/
private $attachment_id;
/**
* #ORM\Column(type="smallint")
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $payment_type;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance Name field cannot be blank")
*/
private $insurance_name;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance # field cannot be blank")
*/
private $insurance_no;
/**
* #ORM\Column(type="decimal", precision=15, scale=2, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $cash;
/**
* One Order has Many Secondary Clients.
* #ORM\ManyToMany(targetEntity="Clients")
* #ORM\JoinTable(name="orders_secondary_clients",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="client_id", referencedColumnName="id")}
* )
*/
private $secondaryClients;
/**
* One Order has Many Employees.
* #ORM\ManyToMany(targetEntity="Employee")
* #ORM\JoinTable(name="orders_employees",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="employee_id", referencedColumnName="id")},
* )
*/
private $employees;
/**
* #ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
*/
private $dates;
/**
* #ORM\Column(type="text", length=100000, nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="smallint")
*/
private $status = 0;
/**
* #ORM\ManyToOne(targetEntity="Patients")
* #ORM\JoinColumn(name="patient_id", referencedColumnName="id")
*/
private $patient;
/**
* #ORM\ManyToOne(targetEntity="Clients")
* #ORM\JoinColumn(name="primary_client_id", referencedColumnName="id")
*/
private $primaryClient;
public function getId(): ?int
{
return $this->id;
}
public function getDateAssigned(): ?\DateTimeInterface
{
return $this->date_assigned;
}
public function setDateAssigned(?\DateTimeInterface $date_assigned): self
{
$this->date_assigned = $date_assigned;
return $this;
}
public function getCreatedBy(): ?int
{
return $this->created_by;
}
public function setCreatedBy(int $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getDateCreated(): \DateTimeInterface
{
return $this->date_created;
}
public function setDateCreated(\DateTimeInterface $dateCreated): self
{
$this->date_created = $dateCreated;
return $this;
}
public function getLastUpdated(): ?\DateTimeInterface
{
return $this->last_updated;
}
public function setLastUpdated(?\DateTimeInterface $last_updated): self
{
$this->last_updated = $last_updated;
return $this;
}
public function getPaymentType(): ?int
{
return $this->payment_type;
}
public function setPaymentType(int $payment_type): self
{
$this->payment_type = $payment_type;
return $this;
}
public function getInsuranceName(): ?string
{
return $this->insurance_name;
}
public function setInsuranceName(?string $insurance_name): self
{
$this->insurance_name = $insurance_name;
return $this;
}
public function getInsuranceNo(): ?string
{
return $this->insurance_no;
}
public function setInsuranceNo(?string $insurance_no): self
{
$this->insurance_no = $insurance_no;
return $this;
}
public function getCash() : float
{
return $this->cash;
}
public function setCash(float $cash): self
{
$this->cash = $cash;
return $this;
}
public function getAttachmentId(): ?int
{
return $this->attachment_id;
}
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getSecondaryClients() : ?PersistentCollection
{
return $this->secondaryClients;
}
public function setSecondaryClients(?array $clients): self
{
$this->secondaryClients = $clients;
return $this;
}
public function getEmployees() : PersistentCollection
{
return $this->employees;
}
public function setEmployees(array $employees): self
{
$this->employees = $employees;
return $this;
}
public function getDates() : PersistentCollection
{
return $this->dates;
}
public function addDate(\DateTime $date): self
{
$orderDate = new OrderDates();
$orderDate->setDate($date);
$orderDate->setOrder($this);
$this->dates[] = $orderDate;
return $this;
}
public function setDates(array $dates): self
{
foreach($dates as $date)
{
$this->addDate(new \DateTime($date));
}
return $this;
}
public function getNotes() : ?string
{
return $this->notes;
}
public function setNotes(?string $notes): self
{
$this->notes = $notes;
return $this;
}
public function getStatus() : int
{
return $this->status;
}
public function setStatus(int $status): self
{
$this->notes = $status;
return $this;
}
public function getGroupSequence()
{
$group = null;
switch($this->payment_type) {
case self::TYPE_InsuranceOnly:
$group = 'insuranceOnly';
break;
case self::TYPE_InsuranceAndCash:
$group = 'insuranceAndCash';
break;
case self::TYPE_CashOnly:
$group = 'cashOnly';
break;
}
return [
[
'Orders',
$group
]
];
}
public function getPatient(): Patients
{
return $this->patient;
}
public function setPatient(Patients $patient) : self
{
$this->patient = $patient;
return $this;
}
public function getPrimaryClient(): Clients
{
return $this->primaryClient;
}
pu]

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 !

Custom query without using doctrine relation

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

Symfony Delete an user with Foreign Key

I have a problem that i can't resolve. That's why i'm coming here.
On my website, an user can upload pictures and videos. When the user try to delete his account, he got a 500 error :
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails"
If i understood, i have to use "joinColumn" "onCascade" and "onDelete" (I want to keep the user's pictures and videos)
My User entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #UniqueEntity(fields={"email"}, message="Cette adresse email est déjà utilisée.")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="boolean")
*/
private $isVerified = false;
/**
* #ORM\OneToMany(targetEntity=Picture::class, mappedBy="author")
*/
private $pictures;
/**
* #ORM\OneToMany(targetEntity=Video::class, mappedBy="author")
*/
private $videos;
/**
* #ORM\ManyToMany(targetEntity=Picture::class, mappedBy="fav")
*/
private $favoris;
/**
* #ORM\ManyToMany(targetEntity=Video::class, mappedBy="fav")
*/
private $fav;
public function __construct()
{
$this->pictures = new ArrayCollection();
$this->videos = new ArrayCollection();
$this->favoris = new ArrayCollection();
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* #see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
/**
* #return Collection|Picture[]
*/
public function getPictures(): Collection
{
return $this->pictures;
}
public function addPicture(Picture $picture): self
{
if (!$this->pictures->contains($picture)) {
$this->pictures[] = $picture;
$picture->setAuthor($this);
}
return $this;
}
public function removePicture(Picture $picture): self
{
if ($this->pictures->removeElement($picture)) {
// set the owning side to null (unless already changed)
if ($picture->getAuthor() === $this) {
$picture->setAuthor(null);
}
}
return $this;
}
/**
* #return Collection|Video[]
*/
public function getVideos(): Collection
{
return $this->videos;
}
public function addVideo(Video $video): self
{
if (!$this->videos->contains($video)) {
$this->videos[] = $video;
$video->setAuthor($this);
}
return $this;
}
public function removeVideo(Video $video): self
{
if ($this->videos->removeElement($video)) {
// set the owning side to null (unless already changed)
if ($video->getAuthor() === $this) {
$video->setAuthor(null);
}
}
return $this;
}
/**
* #return Collection|Picture[]
*/
public function getFavoris(): Collection
{
return $this->favoris;
}
public function addFavori(Picture $favori): self
{
if (!$this->favoris->contains($favori)) {
$this->favoris[] = $favori;
$favori->addFav($this);
}
return $this;
}
public function removeFavori(Picture $favori): self
{
if ($this->favoris->removeElement($favori)) {
$favori->removeFav($this);
}
return $this;
}
/**
* #return Collection|Video[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(Video $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
$fav->addFav($this);
}
return $this;
}
public function removeFav(Video $fav): self
{
if ($this->fav->removeElement($fav)) {
$fav->removeFav($this);
}
return $this;
}
}
My Picture entity :
<?php
namespace App\Entity;
use App\Repository\PictureRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #ORM\Entity(repositoryClass=PictureRepository::class)
*/
class Picture
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=150)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Gedmo\Slug(fields={"title"})
*/
private $slug;
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
/**
* #ORM\Column(type="datetime")
*/
private $publication_date;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="pictures")
* #ORM\JoinColumn(nullable=false)
*/
private $author;
/**
* #ORM\Column(type="string", length=150)
*/
private $category;
/**
* #ORM\Column(type="string", length=50)
*/
private $image;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="favoris")
*/
private $fav;
public function __construct()
{
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getPublicationDate(): ?\DateTimeInterface
{
return $this->publication_date;
}
public function setPublicationDate(\DateTimeInterface $publication_date): self
{
$this->publication_date = $publication_date;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(string $category): self
{
$this->category = $category;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
/**
* #return Collection|User[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(User $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
}
return $this;
}
public function removeFav(User $fav): self
{
$this->fav->removeElement($fav);
return $this;
}
}
My Video entity :
<?php
namespace App\Entity;
use App\Repository\VideoRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=VideoRepository::class)
*/
class Video
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=150)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="datetime")
*/
private $publication_date;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="videos")
* #ORM\JoinColumn(nullable=false)
*/
private $author;
/**
* #ORM\Column(type="string", length=150)
*/
private $category;
/**
* #ORM\Column(type="string", length=50)
*/
private $vid;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="fav")
*/
private $fav;
public function __construct()
{
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getPublicationDate(): ?\DateTimeInterface
{
return $this->publication_date;
}
public function setPublicationDate(\DateTimeInterface $publication_date): self
{
$this->publication_date = $publication_date;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(string $category): self
{
$this->category = $category;
return $this;
}
public function getVid(): ?string
{
return $this->vid;
}
public function setVid(string $vid): self
{
$this->vid = $vid;
return $this;
}
/**
* #return Collection|User[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(User $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
}
return $this;
}
public function removeFav(User $fav): self
{
$this->fav->removeElement($fav);
return $this;
}
}
If you want to - when deleting a user - delete all his pictures and videos as well, you can just add cascade delete to the associations:
/**
* #ORM\OneToMany(targetEntity=Picture::class, mappedBy="author", cascade={"delete"})
*/
private $pictures;
/**
* #ORM\OneToMany(targetEntity=Video::class, mappedBy="author", cascade={"delete"})
*/
private $videos;
If you instead want to keep them and just remove the associoation to the user, add ON DELETE SET NULL to your author_id foreign keys in picture and video tables:
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="videos")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $author;
Then you have to assume in your code that $this->author can be null.

Symfony 4.2 - Doctrine / schema:validate => The table with name 'fablab.appartment_user already exists

beginner here i'm trying to do an API with Api-platform and Symfony. Actually i want to create my database schema and start testing it but when using php bin/console doctrine:schema:validate, i got this error and i cant figure out how to fix it : The table with name 'mydb.appartment_user' already exists
Unfortunately i didnt found an answer on google to my problem :'(
Here is my appartement entity :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\AppartmentRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=AppartmentRepository::class)
*/
class Appartment
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $adress;
/**
* #ORM\Column(type="string", length=255)
*/
private $latitude;
/**
* #ORM\Column(type="string", length=255)
*/
private $longitude;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
*/
private $landlord;
/**
* #ORM\OneToOne(targetEntity=Lock::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $lock_id;
public function __construct()
{
$this->current_tenant = new ArrayCollection();
$this->landlord = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getAdress(): ?string
{
return $this->adress;
}
public function setAdress(string $adress): self
{
$this->adress = $adress;
return $this;
}
public function getLatitude(): ?string
{
return $this->latitude;
}
public function setLatitude(string $latitude): self
{
$this->latitude = $latitude;
return $this;
}
public function getLongitude(): ?string
{
return $this->longitude;
}
public function setLongitude(string $longitude): self
{
$this->longitude = $longitude;
return $this;
}
/**
* #return Collection|User[]
*/
public function getCurrentTenant(): Collection
{
return $this->current_tenant;
}
public function addCurrentTenant(User $currentTenant): self
{
if (!$this->current_tenant->contains($currentTenant)) {
$this->current_tenant[] = $currentTenant;
}
return $this;
}
public function removeCurrentTenant(User $currentTenant): self
{
$this->current_tenant->removeElement($currentTenant);
return $this;
}
/**
* #return Collection|User[]
*/
public function getLandlord(): Collection
{
return $this->landlord;
}
public function addLandlord(User $landlord): self
{
if (!$this->landlord->contains($landlord)) {
$this->landlord[] = $landlord;
}
return $this;
}
public function removeLandlord(User $landlord): self
{
$this->landlord->removeElement($landlord);
return $this;
}
public function getLockId(): ?Lock
{
return $this->lock_id;
}
public function setLockId(Lock $lock_id): self
{
$this->lock_id = $lock_id;
return $this;
}
}
and my user entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
*/
private $firstname;
/**
* #ORM\Column(type="string", length=255)
*/
private $lastname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $profile_picture;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="current_tenant")
*/
private $occupied_appartments;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="landlord")
*/
private $rented_appartments;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="tenant_id")
*/
private $tenant_rentals;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="landlord_id")
*/
private $landlord_rentals;
public function __construct()
{
$this->occupied_appartments = new ArrayCollection();
$this->rented_appartments = new ArrayCollection();
$this->tenant_rentals = new ArrayCollection();
$this->landlord_rentals = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
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 getProfilePicture(): ?string
{
return $this->profile_picture;
}
public function setProfilePicture(?string $profile_picture): self
{
$this->profile_picture = $profile_picture;
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getOccupiedAppartments(): Collection
{
return $this->occupied_appartments;
}
public function addOccupiedAppartment(Appartment $occupied_appartments): self
{
if (!$this->occupied_appartments->contains($occupied_appartments)) {
$this->occupied_appartments[] = $occupied_appartments;
$occupied_appartments->addCurrentTenant($this);
}
return $this;
}
public function removeOccupiedAppartment(Appartment $occupied_appartments): self
{
if ($this->occupied_appartments->removeElement($occupied_appartments)) {
$occupied_appartments->removeCurrentTenant($this);
}
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getRentedAppartments(): Collection
{
return $this->rented_appartments;
}
public function addRentedAppartment(Appartment $rentedAppartment): self
{
if (!$this->rented_appartments->contains($rentedAppartment)) {
$this->rented_appartments[] = $rentedAppartment;
$rentedAppartment->addLandlord($this);
}
return $this;
}
public function removeRentedAppartment(Appartment $rentedAppartment): self
{
if ($this->rented_appartments->removeElement($rentedAppartment)) {
$rentedAppartment->removeLandlord($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getTenantRentals(): Collection
{
return $this->tenant_rentals;
}
public function addTenantRental(Rental $tenantRental): self
{
if (!$this->tenant_rentals->contains($tenantRental)) {
$this->tenant_rentals[] = $tenantRental;
$tenantRental->addTenantId($this);
}
return $this;
}
public function removeTenantRental(Rental $tenantRental): self
{
if ($this->tenant_rentals->removeElement($tenantRental)) {
$tenantRental->removeTenantId($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getLandlordRentals(): Collection
{
return $this->landlord_rentals;
}
public function addLandlordRental(Rental $landlordRental): self
{
if (!$this->landlord_rentals->contains($landlordRental)) {
$this->landlord_rentals[] = $landlordRental;
$landlordRental->addLandlordId($this);
}
return $this;
}
public function removeLandlordRental(Rental $landlordRental): self
{
if ($this->landlord_rentals->removeElement($landlordRental)) {
$landlordRental->removeLandlordId($this);
}
return $this;
}
}
I tried to clear-cache and to force but it didnt work.
Thank's in advance for help and ask me if I forget any details !
add a JoinTable annotation for properties which have ManyToMany relation in Appartment entity
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
* #ORM\JoinTable(name="appartment_current_tenant")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
* #ORM\JoinTable(name="appartment_landlord")
*/
private $landlord;

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

Categories