Doctrine query error unknow column - php

I'm using Doctrine in my Symfony3 project. I'm using the entity manager to get my data from the database but I have an unexpected error which seems to be generated by doctrine.
An exception has been thrown during the rendering of a template ("An exception occurred while executing 'SELECT t0.id AS id_1, t0.date AS date_2, t0.comment AS comment_3, t0.viewed AS viewed_4, t0.error_count AS error_count_5, t0.of_id AS of_id_6, t0.checkpoint_id AS checkpoint_id_7, t8.id AS id_9, t8.name AS name_10, t8.description AS description_11, t8.deleted_at AS deleted_at_12, t8.factory_id AS factory_id_13, t0.operateur_id AS operateur_id_15, t0.factory_id AS factory_id_16 FROM app_check_set t0 LEFT JOIN app_checkpoint t8 ON t0.checkpoint_id = t14.id AND ((t14.deleted_at IS NULL)) WHERE t0.factory_id = ? ORDER BY t0.date DESC LIMIT 5' with params [3]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 't14.id' in 'on clause'").
As I'm not creating the query myself, i would like to know where is this error coming from ? Is it related with my entity configuration ?
The problem is when I want to get my entities Checkset :
public function notificationsAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
return $this->render('AppBundle:Home:notifications.html.twig', array(
'notifications' => $em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId()), array('date' => 'desc'), 5),
'count' => count($em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId(), 'viewed' => false)))
));
}
My entities are like this :
CheckSet:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use UserBundle\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
/**
* CheckSet
*
* #ORM\Table(name="app_check_set")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckSetRepository")
*/
class CheckSet
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResult", mappedBy="checkSet", cascade={"persist"})
*/
private $checkElementResult;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResultObservation", mappedBy="checkSet", cascade={"persist"})
*/
private $observations;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Of", inversedBy="checkSet")
* #ORM\JoinColumn(name="of_id", referencedColumnName="id")
*/
private $of;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="checkSet")
* #ORM\JoinColumn(name="operateur_id", referencedColumnName="id")
*/
private $operateur;
/**
* #ORM\Column(type="boolean", nullable=false, options={"default" : false})
*/
protected $viewed = FALSE;
/**
* #ORM\Column(type="integer", nullable=false)
*/
protected $errorCount;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkSet")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
public function __construct($gamme = null, $of = null, $user = null){
$this->checkElementResult = new ArrayCollection();
$this->observations = new ArrayCollection();
$this->date = new \DateTime();
$this->errorCount = 0;
if ($gamme != null){
$this->checkPoint = $gamme;
}
if ($of != null){
$this->of = $of;
}
if ($user != null){
$this->operateur = $user;
$this->factory = $user->getFactory();
}
}
public function getId(){
return $this->id;
}
public function setDate($date){
$this->date = $date;
return $this;
}
public function getDate(){
return $this->date;
}
public function setErrorCount($errorCount){
$this->errorCount = $errorCount;
return $this;
}
public function getErrorCount(){
return $this->errorCount;
}
public function setComment($comment){
$this->comment = $comment;
return $this;
}
public function getComment(){
return $this->comment;
}
public function setOperateur(User $operateur){
$this->operateur = $operateur;
return $this;
}
public function getOperateur(){
return $this->operateur;
}
public function setOf(Of $of){
$this->of = $of;
return $this;
}
public function getOf(){
return $this->of;
}
public function setFactory(Factory $factory){
$this->factory = $factory;
return $this;
}
public function getFactory(){
return $this->factory;
}
public function setCheckPoint(Checkpoint $checkPoint){
$this->checkPoint = $checkPoint;
return $this;
}
public function getCheckPoint(){
return $this->checkPoint;
}
/*------------------------------------------------------------------------CheckElementResult*/
public function addCheckElementResult(CheckElementResult $cke){
$this->checkElementResult[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeCheckElementResult(CheckElementResult $cke){
$this->checkElementResult->removeElement($cke);
}
public function getcheckElementResult(){
return $this->checkElementResult;
}
/*------------------------------------------------------------------------observations*/
public function addObservations(CheckElementResultObservation $cke){
$this->observations[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeObservations(CheckElementResultObservation $cke){
$this->observations->removeElement($cke);
}
public function getObservations(){
return $this->observations;
}
/*-------------------------------------------------------VIEWED*/
public function setViewed($viewed){
$this->viewed = $viewed;
return $this;
}
public function getViewed(){
return $this->viewed;
}
public function isViewed(){
return $this->viewed;
}
public function countErrors(){
$err = 0;
foreach ($this->checkElementResult as $key => $ckeR) {
foreach ($ckeR->getCheckElement()->getAlert() as $key => $alert) {
if( $alert->getOperator() == "==" && $ckeR->getValue() == $alert->getValue()){
$err++;
}elseif ( $alert->getOperator() == "!=" && $ckeR->getValue() != $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<" && $ckeR->getValue() < $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">" && $ckeR->getValue() > $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<=" && $ckeR->getValue() <= $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">=" && $ckeR->getValue() >= $alert->getValue()) {
$err++;
}
}
}
return $err;
}
public function __toString(){
return $this->of->getName().' '.$this->checkPoint->getName();
}
}
CheckPoint:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Checkpoint
*
* #ORM\Table(name="app_checkpoint")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckpointRepository")
* #Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
*/
class Checkpoint
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElement", mappedBy="checkpoint",cascade={"persist"}, orphanRemoval=true)
* #ORM\OrderBy({"position" = "ASC"})
*/
private $checkElements;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Operation", mappedBy="checkpoint",cascade={"persist"})
*/
private $operation;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkpoints")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckSet", mappedBy="checkPoint")
*/
private $checkSet;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckListOf", mappedBy="checkPoint")
*/
private $checkListOf;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $deletedAt;
public function __construct(){
$this->checkElements = new ArrayCollection();
}
public function getId(){
return $this->id;
}
public function setName($name){
$this->name = $name;
return $this;
}
public function getName(){
return $this->name;
}
public function setDescription($description){
$this->description = $description;
return $this;
}
public function getDescription(){
return $this->description;
}
public function getFactory(){
return $this->factory;
}
public function setFactory($factory){
$this->factory = $factory;
}
/*------------------------------------------------------------------------Checkelements*/
public function addCheckElement(CheckElement $cke){
$this->checkElements[] = $cke;
$cke->setCheckpoint($this);
return $this;
}
public function removeCheckElement(CheckElement $cke){
$this->checkElements->removeElement($cke);
}
public function getCheckElements(){
return $this->checkElements;
}
public function __toString(){
return $this->name;
}
}
The problem could be because of the soft delete but I'm not sure ... The controller I'm calling (notificationsAction) is embed in my header.
In this page (the notifications area) I want to display objects which may have been deleted. The problem happend when the checkpoint I want to display (the one related to the Checkset objects) has been deleted
<!-- NOTIFICATIONS -->
{{ render(controller('AppBundle:Home:notifications', {'request': app.request})) }}

Your issue is actually the same as here.
Your class name is Checkpoint and I guess the file is named checkpoint.php (note that if you are developing on windows, the filename is case-insensitive). All are lowercase.
In your CheckSet class you have
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
The targetEntity is to "AppBundle\Entity\CheckPoint" with capital P.
The issue is that because of this, doctrine create a new alias for a new table (the php comparison is case sensitive github link).
To solve this, change your class name and file to CheckPoint with capital P:
class CheckPoint
{

Related

Symfony 4 Add ManyToMany Entity trough FORM

I am heavily stuck on problem with inserting data trough html.twig when passing one Entity to the other. I am able to add or edit single entities but i cant figure out how to handle adding relations.
Tournament Entity class - unimportant stuff deleted
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Tournament.
*
* #ORM\Table(name="tournament")
* #ORM\Entity(repositoryClass="App\Repository\TournamentRepository")
*/
class Tournament
{
/**
* #var int
*
* #ORM\Column(name="id_tournament", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTournament;
/**
* #var string
*
* #ORM\Column(name="name_of_event", type="string", length=128, nullable=false)
*/
private $nameOfEvent;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=16, nullable=false)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="prizepool", type="string", length=32, nullable=false)
*/
private $prizepool;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=128, nullable=false)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=32, nullable=false)
*/
private $country;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="date", nullable=false)
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="date", nullable=false)
*/
private $endDate;
/**
* #var string|null
*
* #ORM\Column(name="tournament_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $tournamentImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="tourn")
*/
private $events;
/**
* #ORM\OneToMany(targetEntity=Comment::class, mappedBy="tourn_id")
*/
private $comments;
/**
* #ORM\ManyToMany(targetEntity=Team::class, inversedBy="tournaments")
* #ORM\JoinTable(name="playedAt", joinColumns={#ORM\JoinColumn(name="tourn_id", referencedColumnName="id_tournament")},
* inverseJoinColumns={#ORM\JoinColumn(name="team_id", referencedColumnName="ID_Team")})
*/
private $teams;
/**
* #return ArrayCollection
*/
public function getEvents(): Collection
{
return $this->events;
}
/**
* #param ArrayCollection $events
*/
public function setEvents(Collection $events): void
{
$this->events = $events;
}
public function __construct()
{
$this->teams = new ArrayCollection();
$this->events = new ArrayCollection();
$this->comments = new ArrayCollection();
}
public function getIdTournament(): ?int
{
return $this->idTournament;
}
public function addTeam(Team $team): self
{
if (!$this->teams->contains($team)) {
$this->teams[] = $team;
}
return $this;
}
public function removeTeam(Team $team): self
{
if ($this->teams->contains($team)) {
$this->teams->removeElement($team);
}
return $this;
}
}
Team Entity class
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
/**
* Team.
*
* #ORM\Table(name="team")
* #ORM\Entity(repositoryClass="App\Repository\TeamRepository")
*/
class Team
{
/**
* #var int
*
* #ORM\Column(name="ID_Team", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTeam;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=128, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="Region", type="text", length=65535, nullable=false)
*/
private $region;
/**
* #var string
*
* #ORM\Column(name="Coach", type="string", length=64, nullable=false)
*/
private $coach;
/**
* #var string
*
* #ORM\Column(name="Total_Earnings", type="string", length=64, nullable=false)
*/
private $totalEarnings;
/**
* #var string|null
*
* #ORM\Column(name="img_Path", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $imgPath = 'NULL';
/**
* #ORM\OneToMany(targetEntity=Player::class, mappedBy="team", cascade={"persist","remove"})
*/
private $ownedPlayers;
/**
* #var string|null
*
* #ORM\Column(name="player_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $playerImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="team")
*/
private $playedEventAsoc;
/**
* #ORM\ManyToMany(targetEntity=Tournament::class, mappedBy="teams")
*/
private $tournaments;
public function getIdTeam(): ?int
{
return $this->idTeam;
}
public function __construct()
{
$this->tournaments = new ArrayCollection();
$this->playedEventAsoc = new ArrayCollection();
$this->ownedPlayers = new ArrayCollection();
}
public function getPlayedEventAsoc(): Collection
{
return $this->playedEventAsoc;
}
public function setPlayedEventAsoc(Collection $playedEventAsoc): void
{
$this->playedEventAsoc = $playedEventAsoc;
}
public function getStandings(): void
{
$standings = getPlayedEventAsoc().$this->getStandings();
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getRegion(): ?string
{
return $this->region;
}
public function setRegion(string $region): self
{
$this->region = $region;
return $this;
}
public function getCoach(): ?string
{
return $this->coach;
}
public function setCoach(string $coach): self
{
$this->coach = $coach;
return $this;
}
public function getTotalEarnings(): ?string
{
return $this->totalEarnings;
}
public function setTotalEarnings(string $totalEarnings): self
{
$this->totalEarnings = $totalEarnings;
return $this;
}
public function getImgPath(): ?string
{
return $this->imgPath;
}
public function setImgPath(?string $imgPath): self
{
$this->imgPath = $imgPath;
return $this;
}
public function getPlayerImg(): ?string
{
return $this->playerImg;
}
public function setPlayerImg(?string $playerImg): self
{
$this->playerImg = $playerImg;
return $this;
}
public function addPlayer(Player $player): self
{
if (!$this->ownedPlayers->contains($player)) {
$this->ownedPlayers[] = $player;
$player->setTeam($this);
}
return $this;
}
public function removePlayer(Player $player): self
{
if ($this->ownedPlayers->contains($player)) {
$this->ownedPlayers->removeElement($player);
// set the owning side to null (unless already changed)
if ($player->getTeam() === $this) {
$player->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Player[]
*/
public function getOwnedPlayers(): Collection
{
return $this->ownedPlayers;
}
public function addOwnedPlayer(Player $ownedPlayer): self
{
if (!$this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers[] = $ownedPlayer;
$ownedPlayer->setTeam($this);
}
return $this;
}
public function removeOwnedPlayer(Player $ownedPlayer): self
{
if ($this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers->removeElement($ownedPlayer);
// set the owning side to null (unless already changed)
if ($ownedPlayer->getTeam() === $this) {
$ownedPlayer->setTeam(null);
}
}
return $this;
}
public function addEvents(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvents(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function addEvent(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvent(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function getEventData(PersistentCollection $playedEvents): array
{
$eventdata = $playedEvents->getValues();
return $eventdata;
}
public function addPlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if (!$this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc[] = $playedEventAsoc;
$playedEventAsoc->setTeam($this);
}
return $this;
}
public function removePlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if ($this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc->removeElement($playedEventAsoc);
// set the owning side to null (unless already changed)
if ($playedEventAsoc->getTeam() === $this) {
$playedEventAsoc->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Tournament[]
*/
public function getTournaments(): Collection
{
return $this->tournaments;
}
public function addTournament(Tournament $tournament): self
{
if (!$this->tournaments->contains($tournament)) {
$this->tournaments[] = $tournament;
$tournament->addTeam($this);
}
return $this;
}
public function removeTournament(Tournament $tournament): self
{
if ($this->tournaments->contains($tournament)) {
$this->tournaments->removeElement($tournament);
$tournament->removeTeam($this);
}
return $this;
}
}
I am able to edit tournament or team data trough forms and save it to database.
What I am not able is to add data into this relation.
Form Class for this
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('team', EntityType::class, array(
'class' => Team::class,
'multiple' => true,
'expanded' => true,
))
->add('Add Team', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tournament::class
]);
}
Tournament Controller method addTeam - should add Team Entity into Trounament teams collection
/**
* #param Team $team
* #param Request $request
* #Route("/addTeamToEvent/{idTournament}",name="addTeamToEvent")
* #return RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function addTeam(Tournament $tournament, Request $request)
{
$form = $this->createForm(TeamToEvent::class, $tournament);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($tournament);
$this->entityManager->flush();
return new RedirectResponse($this->router->generate('welcome'));
}
return $this->render('welcome/addTeamToEvent.html.twig', ['form' => $form->createView()]);
}
What should be the right aproach? I am totaly lost and i don't know how to do this.

Doctrine entity always saves null on persist even when set

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]

Entity 'models\ForgottenLogin' has a composite identifier but uses an ID generator other than manually assigning (Identity, Sequence)

When I try to do this
$forgottenLoginRepo = $this->doctrine->em->getRepository('models\ForgottenLogin');
$forgottenLogin = $forgottenLoginRepo->findOneBy(
array(
'passwordKey' => $key
)
);
I get this error
Entity 'models\ForgottenLogin' has a composite identifier but uses an
ID generator other than manually assigning (Identity, Sequence). This
is not supported.
My model is
<?php
/**
* Created by PhpStorm.
* User: Manisha.DeSilva
* Date: 06/07/2017
* Time: 13:03
*/
namespace models;
/**
* #Entity
* #Table(name="park_forgotten_login")
*
*/
class ForgottenLogin
{
/**
* #Id
* #Column(name="id", type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
/**
* #Id
* #ManyToOne(targetEntity="Customer")
* #JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
public function getCustomer()
{
return $this->customer;
}
public function setCustomer($value)
{
$this->customer = $value;
}
/**
* #Column(name="password_Key", type="string", nullable=false)
*/
private $passwordKey;
public function getPasswordKey()
{
return $this->passwordKey;
}
public function setPasswordKey($value)
{
$this->passwordKey = $value;
}
/**
* #Column(name="expiry", type="datetime", nullable=false)
*/
private $expiry;
public function getExpiry()
{
return $this->expiry;
}
public function setExpiry($value)
{
$this->expiry = $value;
}
private $forgottenFlag;
public function getForgottenFlag()
{
return $this->forgottenFlag;
}
public function setForgottenFlag($value)
{
$this->forgottenFlag = $value;
}
}

php doctrine orm cant insert joinColumn null

first at all thanks for reading.
I'm a little bit new with Doctrine Orm. My problem is that i have declared a class that has two oneToMany joinColumns, but i need to insert data even when i do not have those joinColumn data.
So, i have a var with three possible values, "factura" | "nota credito" | "nota debito". When "factura" is choosen then i have to add two arrayCollection() to add possible data. But when "nota credito" or "nota debito" choosen i dont have to add the arrays, but when that happends... the new factura object did not insert.
So here is my code of the Librarie and modelCode. Please see just the _construct and the last two joinColumns mapped.
public function insertaFactura($information) {
$cliente = $this->getCollectionByid("Cliente", $information['cob_cliente']);
$factura = new Factura($information, $cliente);
$this->orm->flush();
$this->orm->persist($factura);
if ($information['doc_tipo'] == "factura") {
if ($information['articulos']) {
foreach ($information['articulos'] as $key_venta => $articulos) {
foreach ($articulos as $articulo) {
$ventaArticulo = $this->getCollectionByid("Venta_Articulo", $articulo);
$fva = new Factura_Venta_Articulo();
$fva->setVentaArticulo($ventaArticulo);
$fva->setFactura($factura);
$this->orm->persist($fva);
}
}
$this->orm->flush();
}
}
return $factura->getId();
}
<?php
use \Doctrine\Common\Collections\ArrayCollection;
/**
* Factura
*
* #Table(name="documento_cliente")
* #Entity
*/
class Factura {
/**
* #var integer $id
*
* #Column(name="doc_id", type="integer", nullable=false)
* #Id
* #GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $numero
*
* #Column(name="doc_numero", type="string", length=120, nullable=true)
*/
private $numero;
/**
* #var string $tipo
*
* #Column(name="doc_tipo", type="string")
*/
private $tipo;
/**
* #var string $fecha
*
* #Column(name="doc_fecha", type="date", length=1, nullable=true)
*/
private $fecha;
/**
* #var integer $estado
*
* #Column(name="doc_estado", type="integer", length=120, nullable=true)
*/
private $estado;
/**
* #OneToOne(targetEntity="Cliente", cascade={"persist", "remove"}))
* #JoinColumn(name="doc_cliente_id", referencedColumnName="cli_id")
* */
private $cliente;
/**
* #OneToMany(targetEntity="Factura_Venta_Articulo", mappedBy="factura")
* #JoinColumn(name="fva_ver_id", referencedColumnName="ver_id",nullable=true)
* */
private $venta_articulo;
/**
* #OneToMany(targetEntity="Cobro_factura", mappedBy="factura")
* #JoinColumn(name="cof_id", referencedColumnName="cobro_id",nullable=true)
* */
private $cobros;
public function getId() {
return $this->id;
}
public function getTipo() {
return $this->tipo;
}
public function getNumero() {
return $this->numero;
}
public function getFecha() {
return $this->fecha;
}
public function getEstado() {
return $this->estado;
}
public function getCliente() {
return $this->cliente;
}
public function getVentasArticulo() {
return $this->venta_articulo;
}
public function getCobros() {
return $this->cobros;
}
public function setNumero($numero) {
$this->numero = $numero;
}
public function setTipo($tipo) {
$this->tipo = $tipo;
}
public function setFecha($fecha) {
$this->fecha = $fecha;
}
public function setEstado($estado) {
$this->estado = $estado;
}
public function setCliente($cliente) {
$this->cliente = $cliente;
}
public function __construct($parameters, $cliente) {
$this->setEstado(3);
$this->setFecha(new \DateTime($parameters['factura_fecha']));
$this->setNumero($parameters['factura_numero']);
$this->setCliente($cliente);
$this->setTipo($parameters['doc_tipo']);
if ($parameters['doc_tipo'] == 'factura') {
$this->venta_articulo = new ArrayCollection();
$this->cobros = new ArrayCollection();
}
}
public function actualizar($numero, $fecha, $cliente) {
$this->setNumero($numero);
$this->setFecha(new \DateTime($fecha));
$this->setCliente($cliente);
}
public function totalFactura() {
$total = 0.0;
foreach ($this->venta_articulo as $ventaArticulo) {
$total+=$ventaArticulo->getVentaArticulo()->getIngreso();
}
return $total;
}
public function totalFacturaCobrado() {
$total = 0;
foreach ($this->cobros as $cobro) {
$total+=$cobro->getCobranza();
}
return number_format($total, 2, '.', '');
}
public function totalFacturaACobrar() {
return number_format($this->totalFactura(), 2, '.', '') - number_format($this->totalFacturaCobrado(), 2, '.', '');
}
}

Doctrine 2 Model One-to-Many Many-to-One Queries

I have such doctrine entities:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity(repositoryClass="App\Repository\Page")
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $p_id;
/** #Column(type="string", name="p_title") */
private $p_title;
/** #Column(type="datetime", name="p_created") */
private $p_created_at;
/** #Column(type="datetime", name="p_updated_at") */
private $p_updated_at;
/** #Column(type="text", name="p_abstract") */
private $p_abstract;
/** #Column(type="text", name="p_fulltext", nullable=false) */
private $p_fulltext;
/** #Column(type="string", name="p_author", nullable=true) */
private $p_author;
/** #Column(type="string", name="p_url",nullable=true) */
private $p_url;
/** #Column(type="string", name="p_meta_title",nullable=true) */
private $p_meta_title;
/** #Column(type="string", name="p_meta_keywords",nullable=true) */
private $p_meta_keywords;
/** #Column(type="string", name="p_meta_description",nullable=true) */
private $p_meta_description;
/** #Column(type="string", name="p_status") */
private $p_status;
/**
* #ManyToOne(targetEntity="User", inversedBy="pages")
* #JoinColumn(name="p_u_id", referencedColumnName="u_id")
*/
private $user;
/**
* #OneToMany(targetEntity="App\Entity\Page\Media", mappedBy="pages")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageMedia;
/**
* #OneToMany(targetEntity="App\Entity\Page\Basket", mappedBy="baskets")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageBasket;
public function __construct()
{
$this->pageMedia = new App\Entity\Page\Media();
$this->medias = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
public function setUser(user $user)
{
$this->user = $user;
}
public function setMedia(media $media)
{
$this->pageMedia->setPageAndMedia($this,$media);
}
/**
* Set Page Values
* #var array $values
*/
public function setPageProperties(array $values)
{
$this->p_updated_at = new \DateTime("now");
$this->p_title = $values['p_title'];
$this->p_abstract = $values['p_abstract'];
$this->p_meta_title = $values['p_meta_title'];
$this->p_meta_keywords = $values['p_meta_keywords'];
$this->p_meta_description = $values['p_meta_description'];
$this->p_url = $values['p_url'];
$this->p_fulltext = $values['p_abstract'];
$this->p_author = '';
$this->p_status = 1;
}
}
?>
<?php
namespace App\Entity\Page;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class Basket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $pb_id;
/**
* #ManyToOne(targetEntity="App\Entity\Page")
* #JoinColumn(name="pb_p_id", referencedColumnName="p_id")
*/
private $pages;
/**
* #ManyToOne(targetEntity="App\Entity\Basket",inversedBy="pageBasket")
* #JoinColumn(name="pb_b_id", referencedColumnName="b_id")
*/
private $baskets;
public function __construct()
{
$this->baskets = new ArrayCollection();
$this->pages = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
/**
*
*/
public function setPageAnBasket(page $page,basket $basket)
{
$this->pages[] = $page;
$this->baskets[] = $basket;
}
}
?>
And method in repository:
<?php
namespace App\Repository;
use Doctrine\ORM\EntityRepository;
class Page extends EntityRepository
{
/**
* Find pages by basket Id
* #var int $basketId
* #return array $pages[]
*/
public function findPagesByBasket($basketId)
{
$dql = $this->_em->createQueryBuilder();
$dql->select('u')
->from('App\Entity\Page', 'p')
->leftJoin('p.App\Entity\Page\Basket','pb_b_id = p_id')
->andWhere('pb_b_id = :basketId')
->setParameter('basketId', $basketId);
return $dql->getQuery()->getArrayResult();
}
}
But when I ry to run dql all I'm getting:
string '[Semantical Error] line 0, col 67 near 'pb_b_id = p_id': Error: Class App\Entity\Page has no association named App\Entity\Page\Basket'
What I'm doing wrong because I don't want to use many to many relation because I wanna have additional fields in join table.
I needed a good excuse to make myself a simple test case so here it is.
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity()
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $id;
/**
* #OneToMany(targetEntity="Entity\PageBasket", mappedBy="page")
*/
protected $pageBaskets;
public function __construct()
{
$this->pageBaskets = new ArrayCollection();
}
public function getId() { return $this->id; }
public function getPageBaskets() { return $this->pageBaskets; }
}
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class PageBasket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $id;
/**
* #ManyToOne(targetEntity="Entity\Page")
* #JoinColumn(name="page_id", referencedColumnName="p_id")
*/
private $page;
public function setPage($page)
{
$this->page = $page;
}
public function getId() { return $this->id; }
}
And a working test query
protected function testQuery()
{
$basketId = 1;
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->addSelect('page');
$qb->addSelect('pageBasket');
$qb->from('\Entity\Page','page');
$qb->leftJoin('page.pageBaskets','pageBasket');
$qb->andWhere($qb->expr()->in('pageBasket.id',$basketId));
$query = $qb->getQuery();
$results = $query->getResult();
$page = $results[0];
$pageBaskets = $page->getPageBaskets();
$pageBasket = $pageBaskets[0];
echo 'Result Count ' . count($results) . "\n";
echo 'Page ID ' . $page->getId() . "\n";
echo 'Page Basket ID ' . $pageBasket->getId() . "\n";
echo $query->getSQL() . "\n";
}
The generated sql look like:
SELECT p0_.p_id AS p_id0, p1_.pb_id AS pb_id1, p1_.page_id AS page_id2
FROM page p0_
LEFT JOIN page_basket p1_ ON p0_.p_id = p1_.page_id
WHERE p1_.pb_id IN (1)

Categories