Type conversion error from LifecycleEventArgs - symfony-3.3

I have no idea for this. I'm a beginner of symfony3.
code
/**
* Set createdAt
* #ORM\PrePersist()
* #param \DateTime $createdAt
*
* #return Book
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updateAt
*
* #param \DateTime $updateAt
*
* #return Book
*/
public function setUpdateAt($updateAt)
{
$this->updateAt = $updateAt;
return $this;
}
/**
* Get updateAt
*
* #return \DateTime
*/
public function getUpdateAt()
{
return $this->updateAt;
}
/**
* #ORM\PrePersist()
*/
public function PrePersist() {
if ($this->getCreatedAt() == null) {
$this->setCreatedAt(new \DateTime('now'));
}
$this->setUpdateAt(new \DateTime('now'));
}
/**
* #ORM\PreUpdate()
*/
public function PreUpdate() {
$this->setUpdateAt(new \DateTime('now'));
}
it gives an error report as below :
Error
Could not convert PHP value of type 'Doctrine\ORM\Event\LifecycleEventArgs' to type 'datetime'. Expected one of the following types: null, DateTime
Help me to figure it out.

Related

Doctrine custom entity repository (QueryBuilder)

Howe create custom repository QueryBuilder for Room entity, witch will return all available rooms between two dates. I have two Entities Room.php and Reservation.php In RoomRepository.php i create function findAvailableRooms($from, $to) Hove i create query builder who return all rooms who do not have a reservation in the selected period? Tnx Room.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\AvailableRoom;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Uid\Uuid;
use App\Repository\RoomRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Controller\AvailableRoomController;
/**
* #ApiResource(
* normalizationContext={"groups"={"room:read"}},
* denormalizationContext={"groups"={"room:write"}},
* attributes={
* "pagination_client_items_per_page"=true
* },
* collectionOperations={
* "get",
* "post",
* "get_available"={
* "method"="GET",
* "path"="/rooms/available/{from}/{to}",
* "controller"=AvailableRoomController::class
* }
* }
* )
* #ORM\Entity(repositoryClass=RoomRepository::class)
*/
class Room
{
/**
* #ORM\Id
* #ORM\Column(type="uuid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class=UuidV4Generator::class)
* #Groups({"room:read"})
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Groups({"room:read", "room:write", "reservation:read"})
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
* #Gedmo\Slug(fields={"name"})
* #Groups({"room:read", "room:write"})
*/
private $slug;
/**
* #ORM\Column(type="text", nullable=true)
* #Groups({"room:read", "room:write"})
*/
private $description;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="create")
* #Groups({"room:read", "room:write"})
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="update")
* #Groups({"room:read", "room:write"})
*/
private $updatedAt;
/**
* #ORM\OneToMany(targetEntity=Reservation::class, mappedBy="room")
* #Groups({"room:read", "room:write"})
*/
private $reservations;
public function __construct()
{
$this->reservations = new ArrayCollection();
}
public function getId(): ?Uuid
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* #return Collection|Reservation[]
*/
public function getReservations(): Collection
{
return $this->reservations;
}
public function addReservation(Reservation $reservation): self
{
if (!$this->reservations->contains($reservation)) {
$this->reservations[] = $reservation;
$reservation->setRoom($this);
}
return $this;
}
public function removeReservation(Reservation $reservation): self
{
if ($this->reservations->removeElement($reservation)) {
// set the owning side to null (unless already changed)
if ($reservation->getRoom() === $this) {
$reservation->setRoom(null);
}
}
return $this;
}
}
Reservation.php
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\DateFilter;
use App\Repository\ReservationRepository;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\IdGenerator\UuidV4Generator;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Uid\Uuid;
/**
* #ApiResource(
* normalizationContext={"groups"={"reservation:read"}},
* denormalizationContext={"groups"={"reservation:write"}},
* attributes={
* "pagination_client_items_per_page"=true
* }
* )
* #ApiFilter(DateFilter::class, properties={"dateFrom"})
* #ORM\Entity(repositoryClass=ReservationRepository::class)
*/
class Reservation
{
/**
* #ORM\Id
* #ORM\Column(type="uuid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class=UuidV4Generator::class)
* #Groups({"reservation:read"})
*/
private $id;
/**
* #ORM\Column(type="date")
* #Groups({"reservation:read", "reservation:write", "room:read"})
*/
private $dateFrom;
/**
* #ORM\Column(type="date")
* #Groups({"reservation:read", "reservation:write", "room:read"})
*/
private $dateTo;
/**
* #ORM\Column(type="json", nullable=true)
* #Groups({"reservation:read", "reservation:write", "room:read"})
*/
private $meta = [];
/**
* #ORM\ManyToOne(targetEntity=Room::class, inversedBy="reservations")
* #Groups({"reservation:read", "reservation:write"})
*/
private $room;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="create")
* #Groups({"reservation:read", "reservation:write", "room:read"})
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="update")
* #Groups({"reservation:read", "reservation:write", "room:read"})
*/
private $updatedAt;
public function getId(): ?Uuid
{
return $this->id;
}
public function getDateFrom(): ?\DateTimeInterface
{
return $this->dateFrom;
}
public function setDateFrom(\DateTimeInterface $dateFrom): self
{
$this->dateFrom = $dateFrom;
return $this;
}
public function getDateTo(): ?\DateTimeInterface
{
return $this->dateTo;
}
public function setDateTo(\DateTimeInterface $dateTo): self
{
$this->dateTo = $dateTo;
return $this;
}
public function getMeta(): ?array
{
return $this->meta;
}
public function setMeta(?array $meta): self
{
$this->meta = $meta;
return $this;
}
public function getRoom(): ?Room
{
return $this->room;
}
public function setRoom(?Room $room): self
{
$this->room = $room;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}
Something like the following method placed in your ReservationRepository will fetch the ids of Rooms having a Reservation overlapping a specified date range:
/**
* #param \DateTimeInterface $start
* #param \DateTimeInterface $end
*
* #return array
*/
public function findRoomIdsReservedInDateRange(\DateTimeInterface $start, \DateTimeInterface $end)
{
$result = $this
->createQueryBuilder('r')
->select('r.room.id')
->andWhere('r.dateFrom < :end')
->andWhere('r.dateTo > :start')
->setParameter('start', $start)
->setParameter('end', $end)
->orderBy('r.room.id', 'ASC')
->getQuery()
->getScalarResult()
; // [['id' => 1], ['id' => 2], ['id' => 2], ['id' => 5]]
return array_unique(array_column($result, 'id')); // [1, 2, 5]
}
Then you could call that method from your RoomRepository
$exclude = $reservationRepository->findRoomIdsReservedInDateRange($start, $end);
return $this
->createQueryBuilder('room')
->andWhere('room.id not in :array')
->setParameter('array', $exclude)
->getQuery()
->getResult()
;

ORM ManyToOne Unidirectional fetchAll Object array does not render in phtml Zend Framework 3

The application has built in ZF3. I have to entity with ManyToOne relationship using ORM. The issue is when i render through controller and and if fetch data via index it gives okay result but when i assign that to view and trying to render at phtml it throws an error/
/**
* Subscriptions
*
* #ORM\Table(name="subscriptions", indexes={#ORM\Index(name="CUST_ID", columns={"customer_id"}),#ORM\Index(name="SUB_TYPE_ID", columns={"subscription_type_id"})})
* #ORM\Entity
*/
class Subscriptions
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Application\Entity\SubscriptionType
*
* #ORM\ManyToOne(targetEntity="Application\Entity\SubscriptionType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="subscription_type_id", referencedColumnName="id")
* })
*/
protected $subscriptionType;
//set
public function setSubscriptionType(\Application\Entity\SubscriptionType $subscriptionType = null)
{
$this->subscriptionType = $subscriptionType;
return $this;
}
//get
public function getSubscriptionType(){
return $this->subscriptionType;
}
//other setter and getter....
}
Another Class
/**
* SubscriptionType
*
* #ORM\Table(name="subscription_type")
* #ORM\Entity
*/
class SubscriptionType
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="description", type="text", length=65535, nullable=true)
*/
private $description;
/**
* Get id
*enter code here
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set description
*
* #param string $description
*
* #return SubscriptionType
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
}
Now at controller i have wrote...
//some initiations
class AdminController extends AbstractActionController
{
//other initiations including __construct....
public function usersubscriptionsAction(){
$this->subscriptions = $this->entityManager->getRepository(Subscriptions::class)->findAll();
/*
foreach($this->subscriptions as $subscription){
//if i am checking with this it gives proper output
echo $subscription->getSubscriptionType()->getDescription();
die();
}
*/
return new ViewModel(
array(
"subscriptions" => $this->subscriptions
)
);
}
}
///i have phtml file
<?php foreach ($subscriptions as $subscription): ?>
//below line throwing an error
<?php echo $subscription->getSubscriptionType()->getDescription(); ?>
<?php endforeach; ?>
when i run it throw an erro message
Call to a member function getDescription() on null
You've got the relation mapping incorrect. Corrected the property annotation below:
/**
* #var \Application\Entity\SubscriptionType
*
* #ORM\ManyToOne(targetEntity="Application\Entity\SubscriptionType")
* #ORM\JoinColumn(name="subscription_type_id", referencedColumnName="id")
*/
protected $subscriptionType;
You had
/**
* #var \Application\Entity\SubscriptionType
*
* #ORM\ManyToOne(targetEntity="Application\Entity\SubscriptionType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="subscription_type_id", referencedColumnName="id")
* })
*/
protected $subscriptionType;
The #ORM\JoinColumns is used for when you have a join with multiple columns, please see the docs. Though, the most common usage of JoinColumns is for a JoinTable.

Problems with Doctrine mapping in Symfony

I have been programming a project in the Symfony 3 using the Doctrine ORM. I have main entity called 'Race', which contains some fields and relations to another entities like 'RaceRelationToType', 'RaceRelationToOrganizer' and so on - you can see it in the picture of the database schema bellow. (Only for information, 'RaceRelationTo*' entities are entities which prevents change of original data.)
The problem: The problem becames when I fetch data from database using $this->em->getRepository('AppBundle:Race')->findAll();. Data in database are stored correctly, but If I fetch them, they have wrong data type. raceRelationToOrganizer variable should be of data type RaceRelationToOrganizer, not RaceRelationToSeason and so on.
Everything had worked right until I reset a database. When I insert new race to cleared database, id of raceRelationToSeason is 1, raceRelationToType is 1, raceRelationToOrganizer is 1 ans so on. Problems occured after reset of database (and reset of auto increment).
If ids of all relations are different, than it works OK. Magic? Error? Does anybody know what to do with it? Can you find some problem in files bellow? I have been trying to solve it for hours. Contents of important files are bellow.
I use yaml configuration files for ORM mapping. Race.orm.yml contains:
AppBundle\Entity\Race:
type: entity
table: race
id:
id:
type: integer
generator:
strategy: AUTO
fields:
registrationNumberOfRace:
column: registration_number_of_race
type: integer
length: 4
nullable: false
dateFrom:
column: date_from
type: date
nullable: false
dateTo:
column: date_to
type: date
nullable: false
manyToOne:
raceRelationToSeason:
targetEntity: AppBundle\Entity\RaceRelationToSeason
joinColumn:
name: race_relation_to_season
referencedColumnName: id
onDelete: RESTRICT
nullable: false
fetch: EAGER
cascade: [ persist,remove ]
raceRelationToType:
targetEntity: AppBundle\Entity\RaceRelationToType
joinColumn:
name: race_relation_to_type
referencedColumnName: id
onDelete: RESTRICT
nullable: false
fetch: EAGER
cascade: [ persist,remove ]
raceRelationToOrganizer:
targetEntity: AppBundle\Entity\RaceRelationToOrganizer
joinColumn:
name: race_relation_to_organizer
referencedColumnName: id
onDelete: RESTRICT
nullable: false
fetch: EAGER
cascade: [ persist,remove ]
raceRelationToVenue:
targetEntity: AppBundle\Entity\RaceRelationToVenue
joinColumn:
name: race_relation_to_venue
referencedColumnName: id
onDelete: RESTRICT
nullable: false
fetch: EAGER
cascade: [ persist,remove ]
Entity Race.php contains:
<?php
namespace AppBundle\Entity;
/**
* Class Race
* #package AppBundle\Entity
*/
class Race
{
/**
* #var integer Id of the race
*/
protected $id;
/**
* #var SeasonOfRace
*/
protected $seasonOfRace;
/**
* #var RaceRelationToSeason
*/
protected $raceRelationToSeason;
/**
* #var TypeOfRace
*/
protected $typeOfRace;
/**
* #var RaceRelationToType
*/
protected $raceRelationToType;
/**
* #var integer Registration number of the race which depend on the type of race
*/
protected $registrationNumberOfRace;
/**
* #var OrganizerOfRace
*/
protected $organizerOfRace;
/**
* #var RaceRelationToOrganizer
*/
protected $raceRelationToOrganizer;
/**
* #var VenueOfRace
*/
protected $venueOfRace;
/**
* #var RaceRelationToVenue
*/
protected $raceRelationToVenue;
/**
* #var \DateTime
*/
protected $dateFrom;
/**
* #var \DateTime
*/
protected $dateTo;
/**
* Race constructor.
*/
public function __construct()
{
$this->dateFrom = $this->dateTo = new \DateTime();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return SeasonOfRace
*/
public function getSeasonOfRace()
{
if ($this->raceRelationToSeason) {
if ($this->raceRelationToSeason->getOriginal()) {
$this->seasonOfRace = $this->raceRelationToSeason->getOriginal();
return $this->seasonOfRace;
} else {
return $this->seasonOfRace;
}
} else {
return $this->seasonOfRace;
}
}
/**
* #param SeasonOfRace $seasonOfRace
* #return Race
*/
public function setSeasonOfRace(SeasonOfRace $seasonOfRace)
{
$this->seasonOfRace = $seasonOfRace;
if ($this->seasonOfRace) {
if ($this->raceRelationToSeason) {
$this->raceRelationToSeason->setLabel($this->seasonOfRace->getLabel());
$this->raceRelationToSeason->setShortLabel($this->seasonOfRace->getShortLabel());
$this->raceRelationToSeason->setOriginal($this->seasonOfRace);
} else {
$this->raceRelationToSeason = new RaceRelationToSeason();
$this->raceRelationToSeason->setLabel($this->seasonOfRace->getLabel());
$this->raceRelationToSeason->setShortLabel($this->seasonOfRace->getShortLabel());
$this->raceRelationToSeason->setOriginal($this->seasonOfRace);
}
}
return $this;
}
/**
* #return RaceRelationToSeason
*/
public function getRaceRelationToSeason()
{
return $this->raceRelationToSeason;
}
/**
* #param RaceRelationToSeason $raceRelationToSeason
* #return Race
*/
public function setRaceRelationToSeason(RaceRelationToSeason $raceRelationToSeason)
{
$this->raceRelationToSeason = $raceRelationToSeason;
return $this;
}
/**
* #return TypeOfRace
*/
public function getTypeOfRace()
{
if ($this->raceRelationToType) {
if ($this->raceRelationToType->getOriginal()) {
$this->typeOfRace = $this->raceRelationToType->getOriginal();
return $this->typeOfRace;
} else {
return $this->typeOfRace;
}
} else {
return $this->typeOfRace;
}
}
/**
* #param TypeOfRace $typeOfRace
* #return Race
*/
public function setTypeOfRace(TypeOfRace $typeOfRace)
{
$this->typeOfRace = $typeOfRace;
if ($this->typeOfRace) {
if ($this->raceRelationToType) {
$this->raceRelationToType->setLabel($this->typeOfRace->getLabel());
$this->raceRelationToType->setShortLabel($this->typeOfRace->getShortLabel());
$this->raceRelationToType->setOriginal($this->typeOfRace);
} else {
$this->raceRelationToType = new RaceRelationToType();
$this->raceRelationToType->setLabel($this->typeOfRace->getLabel());
$this->raceRelationToType->setShortLabel($this->typeOfRace->getShortLabel());
$this->raceRelationToType->setOriginal($this->typeOfRace);
}
}
return $this;
}
/**
* #return RaceRelationToType
*/
public function getRaceRelationToType()
{
return $this->raceRelationToType;
}
/**
* #param RaceRelationToType $raceRelationToType
* #return Race
*/
public function setRaceRelationToType(RaceRelationToType $raceRelationToType)
{
$this->raceRelationToType = $raceRelationToType;
return $this;
}
/**
* #return int
*/
public function getRegistrationNumberOfRace()
{
return $this->registrationNumberOfRace;
}
/**
* #param $registrationNumberOfRace
* #return Race
*/
public function setRegistrationNumberOfRace($registrationNumberOfRace)
{
$this->registrationNumberOfRace = $registrationNumberOfRace;
return $this;
}
/**
* #return VenueOfRace
*/
public function getVenueOfRace()
{
if ($this->raceRelationToVenue) {
if ($this->raceRelationToVenue->getOriginal()) {
$this->venueOfRace = $this->raceRelationToVenue->getOriginal();
return $this->venueOfRace;
} else {
return $this->venueOfRace;
}
} else {
return $this->venueOfRace;
}
}
/**
* #param VenueOfRace $venueOfRace
* #return Race
*/
public function setVenueOfRace(VenueOfRace $venueOfRace)
{
$this->venueOfRace = $venueOfRace;
if ($this->venueOfRace) {
if ($this->raceRelationToVenue) {
$this->raceRelationToVenue->setLabel($this->venueOfRace->getLabel());
$this->raceRelationToVenue->setShortLabel($this->venueOfRace->getShortLabel());
$this->raceRelationToVenue->setOriginal($this->venueOfRace);
} else {
$this->raceRelationToVenue = new RaceRelationToVenue();
$this->raceRelationToVenue->setLabel($this->venueOfRace->getLabel());
$this->raceRelationToVenue->setShortLabel($this->venueOfRace->getShortLabel());
$this->raceRelationToVenue->setOriginal($this->venueOfRace);
}
}
return $this;
}
/**
* #return RaceRelationToVenue
*/
public function getRaceRelationToVenue()
{
return $this->raceRelationToVenue;
}
/**
* #param RaceRelationToVenue $raceRelationToVenue
* #return Race
*/
public function setRaceRelationToVenue(RaceRelationToVenue $raceRelationToVenue)
{
$this->raceRelationToVenue = $raceRelationToVenue;
return $this;
}
/**
* #return OrganizerOfRace
*/
public function getOrganizerOfRace()
{
if ($this->raceRelationToOrganizer) {
if ($this->raceRelationToOrganizer->getOriginal()) {
$this->organizerOfRace = $this->raceRelationToOrganizer->getOriginal();
return $this->organizerOfRace;
} else {
return $this->organizerOfRace;
}
} else {
return $this->organizerOfRace;
}
}
/**
* #param OrganizerOfRace $organizerOfRace
* #return Race
*/
public function setOrganizerOfRace(OrganizerOfRace $organizerOfRace)
{
$this->organizerOfRace = $organizerOfRace;
if ($this->organizerOfRace) {
if ($this->raceRelationToOrganizer) {
$this->raceRelationToOrganizer->setLabel($this->organizerOfRace->getLabel());
$this->raceRelationToOrganizer->setShortLabel($this->organizerOfRace->getShortLabel());
$this->raceRelationToOrganizer->setOriginal($this->organizerOfRace);
} else {
$this->raceRelationToOrganizer = new RaceRelationToOrganizer();
$this->raceRelationToOrganizer->setLabel($this->organizerOfRace->getLabel());
$this->raceRelationToOrganizer->setShortLabel($this->organizerOfRace->getShortLabel());
$this->raceRelationToOrganizer->setOriginal($this->organizerOfRace);
}
}
return $this;
}
/**
* #return RaceRelationToOrganizer
*/
public function getRaceRelationToOrganizer()
{
return $this->raceRelationToOrganizer;
}
/**
* #param RaceRelationToOrganizer $raceRelationToOrganizer
* #return Race
*/
public function setRaceRelationToOrganizer(RaceRelationToOrganizer $raceRelationToOrganizer)
{
$this->raceRelationToOrganizer = $raceRelationToOrganizer;
return $this;
}
/**
* #return \DateTime
*/
public function getDateFrom()
{
return $this->dateFrom;
}
/**
* #param \DateTime $dateFrom
* #return $this
*/
public function setDateFrom(\DateTime $dateFrom)
{
$this->dateFrom = $dateFrom;
return $this;
}
/**
* #return \DateTime
*/
public function getDateTo()
{
return $this->dateTo;
}
/**
* #param \DateTime $dateTo
*/
public function setDateTo(\DateTime $dateTo)
{
$this->dateTo = $dateTo;
}
}
I solved it exactly after 23 hours, it was my fault. I want to say sorry to all who have spent their time with trying to help me.
As you can see in the database schema above, there is the table RaceRelationToType that is table between table called Race and table called TypeOfRace. This table is here because when you remove original data from TypeOfRace, data are still stored in a copy in RaceRelationToType+ - it is because of archiving data. It is same with another tables beggining with RaceRelationToXXX.
Mistake was in RaceRelationToOrganizer.php entity. I had extended RaceRelationToOrganizer entity with VenueOfRace entity instead of OrganizerOfRace entity. I don't know why, but It had worked before, but not after reset of database.
So there was no error shown, but Doctrine didn't know what to do with it (fields in all this between-tables are identical) and it mapped random data types. So that's all.
Thank you and sorry!

Catchable Fatal Error: Object of class AppBundle\Entity\Users could not be converted to string

I am new to symfony and doctrine. I have 2 entities in doctrine one is Users and other is ActivityLogs here is the classes.
Users.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Users
*
* #ORM\Table(name="ms_users")
* #ORM\Entity
*/
class Users
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=50)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="verification_tokken", type="string", length=100)
*/
private $verificationTokken;
/**
* #var string
*
* #ORM\Column(name="tokken_expiry_time", type="string", length=50)
*/
private $tokkenExpiryTime;
/**
* #var integer
*
* #ORM\Column(name="is_two_way_auth_enabled", type="boolean")
*/
private $isTwoWayAuthEnabled;
/**
* #var string
*
* #ORM\Column(name="verification_pin", type="string", length=50)
*/
private $verificationPin;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=250)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="date_string", type="string", length=50)
*/
private $dateString;
/**
* #var string
*
* #ORM\Column(name="date_time_string", type="string", length=50)
*/
private $dateTimeString;
/**
* #var integer
*
* #ORM\Column(name="is_active", type="integer")
*/
private $isActive;
/**
* #var integer
*
* #ORM\Column(name="is_deleted", type="integer")
*/
private $isDeleted;
/**
* #var integer
*
* #ORM\Column(name="is_editable", type="integer")
*/
private $isEditable;
/**
* #var string
*
* #ORM\Column(name="last_updated_on", type="string", length=50)
*/
private $lastUpdatedOn;
/**
* #var integer
*
* #ORM\Column(name="school_id", type="integer")
*/
private $schoolId;
/**
* #var integer
*
* #ORM\Column(name="updated_by", type="integer")
*/
private $updatedBy;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set verificationTokken
*
* #param string $verificationTokken
*
* #return Users
*/
public function setVerificationTokken($verificationTokken)
{
$this->verificationTokken = $verificationTokken;
return $this;
}
/**
* Get verificationTokken
*
* #return string
*/
public function getVerificationTokken()
{
return $this->verificationTokken;
}
/**
* Set tokkenExpiryTime
*
* #param string $tokkenExpiryTime
*
* #return Users
*/
public function setTokkenExpiryTime($tokkenExpiryTime)
{
$this->tokkenExpiryTime = $tokkenExpiryTime;
return $this;
}
/**
* Get tokkenExpiryTime
*
* #return string
*/
public function getTokkenExpiryTime()
{
return $this->tokkenExpiryTime;
}
/**
* Set isTwoWayAuthEnabled
*
* #param integer $isTwoWayAuthEnabled
*
* #return Users
*/
public function setIsTwoWayAuthEnabled($isTwoWayAuthEnabled)
{
$this->isTwoWayAuthEnabled = $isTwoWayAuthEnabled;
return $this;
}
/**
* Get isTwoWayAuthEnabled
*
* #return integer
*/
public function getIsTwoWayAuthEnabled()
{
return $this->isTwoWayAuthEnabled;
}
/**
* Set verificationPin
*
* #param string $verificationPin
*
* #return Users
*/
public function setVerificationPin($verificationPin)
{
$this->verificationPin = $verificationPin;
return $this;
}
/**
* Get verificationPin
*
* #return string
*/
public function getVerificationPin()
{
return $this->verificationPin;
}
/**
* Set slug
*
* #param string $slug
*
* #return Users
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set dateString
*
* #param string $dateString
*
* #return Users
*/
public function setDateString($dateString)
{
$this->dateString = $dateString;
return $this;
}
/**
* Get dateString
*
* #return string
*/
public function getDateString()
{
return $this->dateString;
}
/**
* Set dateTimeString
*
* #param string $dateTimeString
*
* #return Users
*/
public function setDateTimeString($dateTimeString)
{
$this->dateTimeString = $dateTimeString;
return $this;
}
/**
* Get dateTimeString
*
* #return string
*/
public function getDateTimeString()
{
return $this->dateTimeString;
}
/**
* Set isActive
*
* #param integer $isActive
*
* #return Users
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return integer
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set isDeleted
*
* #param integer $isDeleted
*
* #return Users
*/
public function setIsDeleted($isDeleted)
{
$this->isDeleted = $isDeleted;
return $this;
}
/**
* Get isDeleted
*
* #return integer
*/
public function getIsDeleted()
{
return $this->isDeleted;
}
/**
* Set isEditable
*
* #param integer $isEditable
*
* #return Users
*/
public function setIsEditable($isEditable)
{
$this->isEditable = $isEditable;
return $this;
}
/**
* Get isEditable
*
* #return integer
*/
public function getIsEditable()
{
return $this->isEditable;
}
/**
* Set lastUpdatedOn
*
* #param string $lastUpdatedOn
*
* #return Users
*/
public function setLastUpdatedOn($lastUpdatedOn)
{
$this->lastUpdatedOn = $lastUpdatedOn;
return $this;
}
/**
* Get lastUpdatedOn
*
* #return string
*/
public function getLastUpdatedOn()
{
return $this->lastUpdatedOn;
}
/**
* Set schoolId
*
* #param integer $schoolId
*
* #return Users
*/
public function setSchoolId($schoolId)
{
$this->schoolId = $schoolId;
return $this;
}
/**
* Get schoolId
*
* #return integer
*/
public function getSchoolId()
{
return $this->schoolId;
}
/**
* Set updatedBy
*
* #param integer $updatedBy
*
* #return Users
*/
public function setUpdatedBy($updatedBy)
{
$this->updatedBy = $updatedBy;
return $this;
}
/**
* Get updatedBy
*
* #return integer
*/
public function getUpdatedBy()
{
return $this->updatedBy;
}
}
AcitivityLogs.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ActivitLogs
*
* #ORM\Table(name="ms_activity_logs")
* #ORM\Entity
*/
class ActivitLogs
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="user_id", type="integer")
*
* #ORM\ManyToOne(targetEntity="Users")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $userId;
/**
* #var string
*
* #ORM\Column(name="activity_log", type="text")
*/
private $activityLog;
/**
* #var string
*
* #ORM\Column(name="user_agent", type="string", length=250)
*/
private $userAgent;
/**
* #var string
*
* #ORM\Column(name="os_platform", type="string", length=250)
*/
private $osPlatform;
/**
* #var string
*
* #ORM\Column(name="ip_address", type="string", length=250)
*/
private $ipAddress;
/**
* #var string
*
* #ORM\Column(name="referer", type="text")
*/
private $referer;
/**
* #var string
*
* #ORM\Column(name="date_string", type="string", length=50)
*/
private $dateString;
/**
* #var string
*
* #ORM\Column(name="date_time_string", type="string", length=50)
*/
private $dateTimeString;
/**
* #var integer
*
* #ORM\Column(name="is_active", type="integer")
*/
private $isActive;
/**
* #var integer
*
* #ORM\Column(name="is_deleted", type="integer")
*/
private $isDeleted;
/**
* #var integer
*
* #ORM\Column(name="is_editable", type="integer")
*/
private $isEditable;
/**
* #var string
*
* #ORM\Column(name="last_updated_on", type="string", length=50)
*/
private $lastUpdatedOn;
/**
* #var integer
*
* #ORM\Column(name="school_id", type="integer")
*/
private $schoolId;
/**
* #var integer
*
* #ORM\Column(name="updated_by", type="integer")
*/
private $updatedBy;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* #param integer $userId
*
* #return ActivitLogs
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set activityLog
*
* #param string $activityLog
*
* #return ActivitLogs
*/
public function setActivityLog($activityLog)
{
$this->activityLog = $activityLog;
return $this;
}
/**
* Get activityLog
*
* #return string
*/
public function getActivityLog()
{
return $this->activityLog;
}
/**
* Set userAgent
*
* #param string $userAgent
*
* #return ActivitLogs
*/
public function setUserAgent($userAgent)
{
$this->userAgent = $userAgent;
return $this;
}
/**
* Get userAgent
*
* #return string
*/
public function getUserAgent()
{
return $this->userAgent;
}
/**
* Set osPlatform
*
* #param string $osPlatform
*
* #return ActivitLogs
*/
public function setOsPlatform($osPlatform)
{
$this->osPlatform = $osPlatform;
return $this;
}
/**
* Get osPlatform
*
* #return string
*/
public function getOsPlatform()
{
return $this->osPlatform;
}
/**
* Set ipAddress
*
* #param string $ipAddress
*
* #return ActivitLogs
*/
public function setIpAddress($ipAddress)
{
$this->ipAddress = $ipAddress;
return $this;
}
/**
* Get ipAddress
*
* #return string
*/
public function getIpAddress()
{
return $this->ipAddress;
}
/**
* Set referer
*
* #param string $referer
*
* #return ActivitLogs
*/
public function setReferer($referer)
{
$this->referer = $referer;
return $this;
}
/**
* Get referer
*
* #return string
*/
public function getReferer()
{
return $this->referer;
}
/**
* Set dateString
*
* #param string $dateString
*
* #return ActivitLogs
*/
public function setDateString($dateString)
{
$this->dateString = $dateString;
return $this;
}
/**
* Get dateString
*
* #return string
*/
public function getDateString()
{
return $this->dateString;
}
/**
* Set dateTimeString
*
* #param string $dateTimeString
*
* #return ActivitLogs
*/
public function setDateTimeString($dateTimeString)
{
$this->dateTimeString = $dateTimeString;
return $this;
}
/**
* Get dateTimeString
*
* #return string
*/
public function getDateTimeString()
{
return $this->dateTimeString;
}
/**
* Set isActive
*
* #param integer $isActive
*
* #return ActivitLogs
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return integer
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set isDeleted
*
* #param integer $isDeleted
*
* #return ActivitLogs
*/
public function setIsDeleted($isDeleted)
{
$this->isDeleted = $isDeleted;
return $this;
}
/**
* Get isDeleted
*
* #return integer
*/
public function getIsDeleted()
{
return $this->isDeleted;
}
/**
* Set isEditable
*
* #param integer $isEditable
*
* #return ActivitLogs
*/
public function setIsEditable($isEditable)
{
$this->isEditable = $isEditable;
return $this;
}
/**
* Get isEditable
*
* #return integer
*/
public function getIsEditable()
{
return $this->isEditable;
}
/**
* Set lastUpdatedOn
*
* #param string $lastUpdatedOn
*
* #return ActivitLogs
*/
public function setLastUpdatedOn($lastUpdatedOn)
{
$this->lastUpdatedOn = $lastUpdatedOn;
return $this;
}
/**
* Get lastUpdatedOn
*
* #return string
*/
public function getLastUpdatedOn()
{
return $this->lastUpdatedOn;
}
/**
* Set schoolId
*
* #param integer $schoolId
*
* #return ActivitLogs
*/
public function setSchoolId($schoolId)
{
$this->schoolId = $schoolId;
return $this;
}
/**
* Get schoolId
*
* #return integer
*/
public function getSchoolId()
{
return $this->schoolId;
}
/**
* Set updatedBy
*
* #param integer $updatedBy
*
* #return ActivitLogs
*/
public function setUpdatedBy($updatedBy)
{
$this->updatedBy = $updatedBy;
return $this;
}
/**
* Get updatedBy
*
* #return integer
*/
public function getUpdatedBy()
{
return $this->updatedBy;
}
}
I have a simple ManyToOne Relationship between these two tables on userId field.
Here is the code with i m trying to add the data in to database with doctrine.
public function checkDatabaseAction(){
$user = new Users();
$user->setDateString(date('Y-m-d'))
->setDateTimeString(date('Y-m-d H:i:s'))
->setIsActive(1)
->setIsDeleted(0)
->setIsEditable(1)
->setIsTwoWayAuthEnabled(0)
->setLastUpdatedOn(date('Y-m-d H:i:s'))
->setSchoolId(1)
->setSlug('abc-123')
->setTokkenExpiryTime(date('Y-m-d'))
->setUpdatedBy(1)
->setUsername('ahmedali5530')
->setVerificationPin('1122')
->setVerificationTokken('hskajdhfkjlh435kh34k5jh435');
$log = new ActivitLogs();
$log->setActivityLog('A log')
->setDateString(date('Y-m-d'))
->setDateTimeString(date('Y-m-d H:i:s'))
->setIpAddress('192.168.1.16')
->setIsActive(1)
->setIsDeleted(0)
->setIsEditable(1)
->setLastUpdatedOn(date('Y-m-d H:i:s'))
->setOsPlatform('Windows 7')
->setReferer('http://localhost/symfony')
->setSchoolId(1)
->setUpdatedBy(1)
->setUserAgent('Chrome')
->setUserId($user);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->persist($log);
$em->flush();
$allocateCourses = $em->getRepository('AppBundle:AllocateCourses')->findBy(array('isActive'=>1));
return $this->render(':main:form.html.php',array(
'data' => $allocateCourses,
));
}
When I execute this code I received the error:-
An exception occurred while executing 'INSERT INTO ms_activity_logs (user_id, activity_log, user_agent, os_platform, ip_address, referer, date_string, date_time_string, is_active, is_deleted, is_editable, last_updated_on, school_id, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [{}, "A log", "Chrome", "Windows 7", "192.168.1.16", "http://localhost/symfony", "2015-12-22", "2015-12-22 16:53:55", 1, 0, 1, "2015-12-22 16:53:55", 1, 1]:
Catchable Fatal Error: Object of class AppBundle\Entity\Users could not be converted to string
Any suggestions how to fix this error.
Ok I got the answer.
I added the new private property in ActivityLogs.php and told Doctrine to generate the entity. Doctrine created getter and setters for that property. This fixed my problem.
Here is the code I added:
/**
* #ORM\ManyToOne(targetEntity="Users", inversedBy="ActivityLogs")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;

Doctrine insert table using joined table entities as reference

I have spent the last day trying to find a solution to a problem that I am having and now turn to you to see if you can offer some advice.
Ill start with the table and then the entity
I have three tables,
table_a
table_b
table_c
each table row has a unique id
table_c contains a reference to table_a_id and to table_b_id
This reference should be unidirectional as table_a and table_b have no need to ever know of table_c's existence.
Also, there is no cascading, if an id from table_a or table_b does not exist, then table_c should not be able to insert a row.
ok, now for entities. (I am going to cut out irrelevant code to keep it short)
Entity A defines table_a
/**
* A
* #ORM\Entity(repositoryClass="Sample\Bundle\MyBundle\Entity\ARepository")
* #ORM\Table("table_a")
*/
class A
{
/**
* #var integer
*
* #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;
/**
* Get id
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
* #param string $name
* #return A
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
}
Entity B defines table_b
/**
* B
*
* #ORM\Table("table_b")
* #ORM\Entity
*/
class B
{
/**
* #var integer
* #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;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
* #param string $name
* #return B
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
}
Entity C maps table_c and has many to one relationships with table_a and table_b
/**
* C
*
* #ORM\Table("table_c")
* #ORM\Entity(repositoryClass="Sample\Bundle\MyBundle\Entity\CRepository")
*/
class PricesAverage
{
/**
* #var integer
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Sample\Bundle\MyBundle\Entity\A
* #ORM\ManyToOne(targetEntity="Sample\Bundle\MyBundle\Entity\A", inversedBy="id")
* #ORM\JoinColumn(name="a_id",unique=false)
*/
private $a;
/**
* #var \Sample\Bundle\MyBundle\Entity\B
* #ORM\ManyToOne(targetEntity="Sample\Bundle\MyBundle\Entity\B", inversedBy="id")
* #ORM\JoinColumn(name="b_id",unique=false)
*/
private $b;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return A
*/
public function getA() {
return $this->a;
}
/**
* #param A $a
* #return $this
*/
public function setA($a) {
$this->a = $a;
return $this;
}
/**
* #return B
*/
public function getB() {
return $this->b;
}
/**
* #param B $b
* #return $this
*/
public function setB($b) {
$this->b = $b;
return $this;
}
}
No what I do is the following. (this is just simplified logic but it is the same process)
$days = 5;
$aCollection = {get collection of A's)
for($i = 0,$i<$days,$i++){
foreach($aCollection as $a){
$b = {get a single b}
$c = new C();
$c->setA($a)
->setB($b);
{use doctrine to persist and flush $c}
}
}
What is happening is that on the first insert the id for a is correct, but on the second insert, doctrine seems to think that competitor is a new entity and tries to persist and create a new id.
I have dumped my collection without activating the doctrine insert and I see that the id on A is correct, I then do the same thing after doctrine and find that doctrine is somehow clearing away my object.
How can I resolve this?
UPDATE:
I resolved this issue.
The problem that I was having is that the related entity was being removed from the entity manager after I did my batch insert.
The was a result of doing clear after every flush.
I moved clear to the end of the process so I flush as much as I need but only clear once.