Saving in database entity with 2 oneToMany relationship - php

i explain my problem, asking sorry for my english!
I have 2 entity: Projects and Operations. Each projects can have more operations, each operation can have different price.
So, i have created a new entity ProgettoOperazionePrezzo
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="prezzo", type="decimal")
*/
private $prezzo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set prezzo
*
* #param float $prezzo
* #return ProgettoOperazionePrezzo
*/
public function setPrezzo($prezzo)
{
$this->prezzo = $prezzo;
return $this;
}
/**
* Get prezzo
*
* #return float
*/
public function getPrezzo()
{
return $this->prezzo;
}
/**
* #ORM\ManyToOne(targetEntity="Progetto")
* #ORM\JoinColumn(name="progetto_id", referencedColumnName="id")
**/
private $progetto;
/**
* Set progetto
*
* #param \Management\ProgettiBundle\Entity\Progetto $progetto
* #return ProgettoOperazionePrezzo
*/
public function setProgetto(\Management\ProgettiBundle\Entity\Progetto $progetto = null)
{
$this->progetto = $progetto;
return $this;
}
/**
* Get progetto
*
* #return \Management\ProgettiBundle\Entity\Progetto
*/
public function getProgetto()
{
return $this->progetto;
}
/**
* #ORM\ManyToOne(targetEntity="Operazione")
* #ORM\JoinColumn(name="operazione_id", referencedColumnName="id")
**/
private $operazione;
/**
* Set operazione
*
* #param \Management\ProgettiBundle\Entity\Operazione $operazione
* #return ProgettoOperazionePrezzo
*/
public function setOperazione(\Management\ProgettiBundle\Entity\Operazione $operazione = null)
{
$this->operazione = $operazione;
return $this;
}
/**
* Get operazione
*
* #return \Management\ProgettiBundle\Entity\Operazione
*/
public function getOperazione()
{
return $this->operazione;
}
Now i want create a form to save in database all the operations that i chose with checkbutton.
$operazione = new ProgettoOperazionePrezzo();
$progetto = $this->getDoctrine()->getRepository('ManagementProgettiBundle:ProgettoOperazionePrezzo')->find($id_progetto);
$form = $this->createFormBuilder($operazione)
->add('operazione','entity',array(
'label'=>'Operazioni da effettuare:',
'multiple'=>true,
'expanded'=>true,
'class'=>'ManagementProgettiBundle:Operazione',
'property'=>'nome',
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('u')
->orderBy('u.nome', 'ASC');
}))
->add('Passo successivo','submit');
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$operazione->setProgetto($progetto);
$em->persist($operazione);
$em->flush();
//return $this->redirect($this->generateUrl('management_progetti_nuovo_progetto_p3',array('id_progetto'=>$id_progetto)));
}
I have no problem to show the form...but it dwsnt works when i try to save in database my choices cause it give me this error:
Catchable Fatal Error: Argument 1 passed to Management\ProgettiBundle\Entity\ProgettoOperazionePrezzo::setOperazione() must be an instance of Management\ProgettiBundle\Entity\Operazione, instance of Doctrine\Common\Collections\ArrayCollection given, called in D:\xampp\htdocs\alemanno_management\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php on line 345 and defined in D:\xampp\htdocs\alemanno_management\src\Management\ProgettiBundle\Entity\ProgettoOperazionePrezzo.php line 108
What am i doing of wrong?!!?maybe all??please...can u tell me how can i resolve this?!

Because you fetch multiple results from database, your $progetto variable will contain an instance of ArrayCollection, over which you should iterate. Because your query contains an id which should be unique, I assume that you want to fetch only one results:
$progetto = $this->getDoctrine()->getRepository('ManagementProgettiBundle:ProgettoOperazionePrezzo')->findOneBy(array('id' => $id_progetto));
Now your $progetto variable should point to an instance of Management\ProgettiBundle\Entity\Operazione.

Try to use next entity, please:
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="prezzo", type="decimal")
*/
private $prezzo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set prezzo
*
* #param float $prezzo
* #return ProgettoOperazionePrezzo
*/
public function setPrezzo($prezzo)
{
$this->prezzo = $prezzo;
return $this;
}
/**
* Get prezzo
*
* #return float
*/
public function getPrezzo()
{
return $this->prezzo;
}
/**
* #ORM\ManyToOne(targetEntity="Progetto")
* #ORM\JoinColumn(name="progetto_id", referencedColumnName="id")
**/
private $progetto;
/**
* Set progetto
*
* #param \Management\ProgettiBundle\Entity\Progetto $progetto
* #return ProgettoOperazionePrezzo
*/
public function setProgetto(\Management\ProgettiBundle\Entity\Progetto $progetto = null)
{
$this->progetto = $progetto;
return $this;
}
/**
* Get progetto
*
* #return \Management\ProgettiBundle\Entity\Progetto
*/
public function getProgetto()
{
return $this->progetto;
}
public function __construct() {
$this->operazione = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\ManyToOne(targetEntity="Operazione")
* #ORM\JoinColumn(name="operazione_id", referencedColumnName="id")
**/
private $operazione;
/**
* Set operazione
*
* #param \Doctrine\Common\Collections\ArrayCollection $operazione
* #return ProgettoOperazionePrezzo
*/
public function setOperazione(\Doctrine\Common\Collections\ArrayCollection $operazione = null)
{
$this->operazione = $operazione;
return $this;
}
/**
* Get operazione
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getOperazione()
{
return $this->operazione;
}

Related

Symfony Could not determine access type when using EntityType form builder

I have 2 entities Cars and Parts and I want to be able to create new Car with multiple parts. For this reason I made this form in CarsType
$builder->
add('make')->
add('model')->
add('travelledDistance')->
add('parts',EntityType::class,array(
'class' => Parts::class,
'choice_label'=>"name",
'query_builder' => function(PartsRepository $partsRepository){
return $partsRepository->getAllPartsForCarsForm();
},
'multiple' => true
));
It gives me this error
Could not determine access type for property "parts" in class
"AppBundle\Entity\Cars".
Here is my entity Cars
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Cars
*
* #ORM\Table(name="cars")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
*/
class Cars
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Make", type="string", length=255)
*/
private $make;
/**
* #var string
*
* #ORM\Column(name="Model", type="string", length=255)
*/
private $model;
/**
* #var int
*
* #ORM\Column(name="TravelledDistance", type="bigint")
*/
private $travelledDistance;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
* #ORM\JoinTable(
* name="Parts_Cars",
* joinColumns={
* #ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
* })
*/
private $parts;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set make
*
* #param string $make
*
* #return Cars
*/
public function setMake($make)
{
$this->make = $make;
return $this;
}
/**
* Get make
*
* #return string
*/
public function getMake()
{
return $this->make;
}
/**
* Set model
*
* #param string $model
*
* #return Cars
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* Get model
*
* #return string
*/
public function getModel()
{
return $this->model;
}
/**
* Set travelledDistance
*
* #param integer $travelledDistance
*
* #return Cars
*/
public function setTravelledDistance($travelledDistance)
{
$this->travelledDistance = $travelledDistance;
return $this;
}
/**
* Get travelledDistance
*
* #return int
*/
public function getTravelledDistance()
{
return $this->travelledDistance;
}
/**
* #return mixed
*/
public function getParts()
{
return $this->parts;
}
}
And in case it matters here is my Parts entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Parts
*
* #ORM\Table(name="parts")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PartsRepository")
*/
class Parts
{
/**
* #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="Price", type="decimal", precision=10, scale=2)
*/
private $price;
/**
* #var int
*
* #ORM\Column(name="Quantity", type="integer")
*/
private $quantity;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Suppliers", inversedBy="parts")
* #ORM\JoinColumn(name="Supplier_Id", referencedColumnName="id")
*/
private $supplier;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
*/
private $cars;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Parts
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Parts
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return Parts
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* #return mixed
*/
public function getSupplier()
{
return $this->supplier;
}
/**
* #return mixed
*/
public function getCars()
{
return $this->cars;
}
public function __toString()
{
return $this->getName();
}
}
To save time here is the mapping between the 2 entities as well as the property parts in Cars
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
* #ORM\JoinTable(
* name="Parts_Cars",
* joinColumns={
* #ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
* })
*/
private $parts;
and In Parts
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
*/
private $cars;
Here is the newAction in CarsController
/**
* Creates a new car entity.
*
* #Route("/new", name="cars_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$carsRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Cars');
$car = new Cars();
$form = $this->createForm('AppBundle\Form\CarsType', $car);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($car);
$em->flush();
return $this->redirectToRoute('cars_show', array('id' => $car->getId()));
}
return $this->render('cars/new.html.twig', array(
'car' => $car,
'form' => $form->createView(),
));
}
My question is - How can I make it so that I can create new Car with several Parts and to save the relationship in the database so that when I retrieve the Car I can get the parts as well?
Basically how to make it so when I create a new car the relationship is saved in the parts_cars table which holds the id's?
Let Doctrine do the JOIN work
Since you're doing a ManyToMany (EntityToEntity), the #JoinColumn directives are not needed.
Try removing it from the Cars entity.
Cars
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
*/
$parts
The only cases in which you need to specify the JoinColumns are:
Joining against self
Joining where the primary key is not the Entity ID.
Need to define fields in the join_table
Would be MUCH easier in this case to do A OneToMany J ManyToOne B
Since you're doing none of the above, Doctrine is having trouble accessing the Entities' IDENTITY fields for the join.

Doctrine Get the result of a DQL Query in a nested form

I have the following problem:
I have the following method that fetches the GPS points of a vessel:
/**
* #param array $mmsids
* #param unknown $longituteMin
* #param unknown $longtitudeMax
* #param unknown $latitudeMin
* #param unknown $latitudeMax
* #param \Datetime $timeInterval
*
* #throws EmptyParamGivenException
* #throws Exception
*
* #return Vesel[] with their routes
*/
public function getRoutes(array $mmsids=[],
$longituteMin=null,
$longtitudeMax=null,
$latitudeMin=null,
$latitudeMax=null,
\DateTime $fromDate=null,
\DateTime $toDate=null
) {
$em=$this->getEntityManager();
$query=$em->createQueryBuilder('v')
->from('AppBundle:Vesel', 'v')
->innerJoin('v.veselMoveStatuses','m')
->select('v.mmsi,m.logtitude,m.latitude,m.timestamp')
->addOrderBy('v.mmsi','ASC')
->addOrderBy('m.timestamp','DESC');
if(!empty($longituteMin)){
$query->andWhere('m.logtitude >= :long_min')->setParameter(':long_min',$longituteMin);
}
if(!empty($longtitudeMax)) {
$query->andWhere('m.logtitude <= :long_max')->setParameter(':long_max',$longituteMax);
}
if(!empty($latitudeMin)){
$query->andWhere('m.latitude >= :lat_min')->setParameter(':lat_min',$latitudeMin);
}
if(!empty($latitudeMax)){
$query->andWhere('m.latitude <= :lat_max')->setParameter(':lat_max',$latitudeMin);
}
if(!empty($mmsids)){
$query->andWhere('v.mmsi IN (:mmsids)')->setParameter('mmsids', $mmsids,\Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
$paramsToValidate=[RouteInputParameter::PARAM_DATE_FROM=>$fromDate,RouteInputParameter::PARAM_DATE_TO=>$toDate];
if($fromDate!==null && $toDate!==null){
InputValidator::dateRangeValidation($paramsToValidate,RouteInputParameter::PARAM_DATE_FROM,RouteInputParameter::PARAM_DATE_TO);
$query->andWhere('m.timestamp BETWEEN :date_min AND :date_max')
->setParameters(['date_min'=>$fromDate,'date_max'=>$toDate]);
} else if($fromDate!==null) {
$query->andWhere('m.timestamp <= :date_min')
->setParameters(['date_min'=>$fromDate]);
} else if($toDate!==null) {
$query->where('m.timestamp >= :date_max')
->setParameters(['date_max'=>$toDate]);
}
$query = $query->getQuery();
return $query->getResult();
}
What I want to achieve it that I want to generate the result in a nested way like that:
[
[
"mmsi"=>"^somevalue^"
points=>[
"longtitude":"^longtitude_value^",
"latitude":"^latitude_value^",
"time":"^time_value^"
],
....
],
....
]
do you have any idea if there is an internal Doctrine mechanism that allows me to do this or should I implement my own?
The Vessel Entity is:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="vessel",indexes={
* #ORM\Index(name="mmsi",columns={"mmsi"})
* })
*/
class Vesel
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #var integer
*/
private $id;
/**
* #ORM\Column(type="integer",name="mmsi")
* #var integer
*/
private $mmsi;
/**
* #ORM\OneToMany(targetEntity="VesselMoveStatus",mappedBy="vesel")
* #var \Doctrine\Common\Collections\Collection
*/
private $veselMoveStatuses;
/**
* Constructor
*/
public function __construct($mmsi)
{
$this->veselMoveStatuses = new \Doctrine\Common\Collections\ArrayCollection();
$this->setMmsi($mmsi);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set mmsi
*
* #param integer $mmsi
*
* #return Vesel
*/
public function setMmsi($mmsi)
{
$this->mmsi = $mmsi;
return $this;
}
/**
* Get mmsi
*
* #return integer
*/
public function getMmsi()
{
return $this->mmsi;
}
/**
* Add veselMoveStatus
*
* #param \AppBundle\Entity\VesselMoveStatus $veselMoveStatus
*
* #return Vesel
*/
public function addVeselMoveStatus(\AppBundle\Entity\VesselMoveStatus $veselMoveStatus)
{
$this->veselMoveStatuses[] = $veselMoveStatus;
return $this;
}
/**
* Remove veselMoveStatus
*
* #param \AppBundle\Entity\VesselMoveStatus $veselMoveStatus
*/
public function removeVeselMoveStatus(\AppBundle\Entity\VesselMoveStatus $veselMoveStatus)
{
$this->veselMoveStatuses->removeElement($veselMoveStatus);
}
/**
* Get veselMoveStatuses
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVeselMoveStatuses()
{
return $this->veselMoveStatuses;
}
}
And is related into VesselMoveStatus entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Vesel;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\VeselRouteRepository")
* #ORM\Table(name="vessel_position_status",indexes={
* #ORM\Index(name="position",columns={"long","lat"})
* })
*/
class VesselMoveStatus
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id=null;
/**
* #ORM\ManyToOne(targetEntity="Vesel",inversedBy="veselMoveStatuses")
* #ORM\JoinColumn(name="vesel_id", referencedColumnName="id")
* #var Vesel
*/
private $vesel=null;
/**
* #ORM\Column(name="status",type="integer")
* #var integer|null
*/
private $status=null;
/**
* #ORM\Column(name="speed",type="integer")
* #var integer|null
*/
private $speed=null;
/**
* #ORM\Column(name="long",type="float")
* #var float|null
*/
private $logtitude=null;
/**
* #ORM\Column(name="lat",type="float")
* #var float|null
*/
private $latitude=null;
/**
* #ORM\Column(name="course",type="integer")
* #var integer|null
*/
private $course=null;
/**
* #ORM\Column(name="heading",type="integer")
* #var integer|null
*/
private $heading=null;
/**
* #ORM\Column(name="rotation",type="integer")
* #var integer|null
*/
private $rotation=null;
/**
* #ORM\Column(name="timestamp",type="datetime")
* #var Datetime|null
*/
private $timestamp=null;
public function __construct(
Vesel $vesel=null,
$status=null,
$speed=null,
$long=null,
$lat=null,
$course=null,
$heading=null,
$rotation=null,
$timestamp=null
){
$this->setVesel($vesel)
->setStatus($status)
->setSpeed($speed)
->setLogtitude($long)
->setLatitude($lat)
->setCourse($course)
->setHeading($heading)
->setRotation($rotation)
->setTimestamp($timestamp);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set mmsi
*
* #param integer $mmsi
*
* #return VesselMoveStatus
*/
public function setMmsi($mmsi)
{
$this->mmsi = $mmsi;
return $this;
}
/**
* Get mmsi
*
* #return integer
*/
public function getMmsi()
{
return $this->mmsi;
}
/**
*
* #param integer $status
* #return \AppBundle\Entity\VesselMoveStatus
*/
public function setStatus($status)
{
$this->status=$status;
return $this;
}
/**
*
* #return \AppBundle\Entity\integer|NULL
*/
public function getStatus()
{
return $this->status;
}
/**
* Set speed
*
* #param integer $speed
*
* #return VesselMoveStatus
*/
public function setSpeed($speed)
{
$this->speed = $speed;
return $this;
}
/**
* Get speed
*
* #return float
*/
public function getSpeed()
{
return $this->speed/10;
}
/**
* Set logtitude
*
* #param integer $logtitude
*
* #return VesselMoveStatus
*/
public function setLogtitude($logtitude)
{
$this->logtitude = $this->sanitizeGpsCoordinate($logtitude);
return $this;
}
/**
* Get logtitude
*
* #return float
*/
public function getLogtitude()
{
return $this->logtitude;
}
/**
* Set latitude
*
* #param integer $latitude
*
* #return VesselMoveStatus
*/
public function setLatitude($latitude)
{
$this->latitude = $this->sanitizeGpsCoordinate($latitude);
return $this;
}
/**
* Get latitude
*
* #return float
*/
public function getLatitude()
{
$latitude=$this->latitude;
return $latitude;
}
/**
* Set course
*
* #param integer $course
*
* #return VesselMoveStatus
*/
public function setCourse($course)
{
$this->course = $course;
return $this;
}
/**
* Get course
*
* #return integer
*/
public function getCourse()
{
return $this->course;
}
/**
* Set heading
*
* #param integer $heading
*
* #return VesselMoveStatus
*/
public function setHeading($heading)
{
$this->heading = $heading;
return $this;
}
/**
* Get heading
*
* #return integer
*/
public function getHeading()
{
return $this->heading;
}
/**
* Set rotation
*
* #param integer $rotation
*
* #return VesselMoveStatus
*/
public function setRotation($rotation)
{
$this->rotation = $rotation;
return $this;
}
/**
* Get rotation
*
* #return integer
*/
public function getRotation()
{
return $this->rotation;
}
/**
* Set timesptamp
*
* #param string $timesptamp
*
* #return VesselMoveStatus
*/
public function setTimestamp($timesptamp)
{
$this->timestamp = date_create_from_format("Y-m-d H:i:s.u",$timesptamp);
return $this;
}
/**
* Get timesptamp
*
* #return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* Set vesel
*
* #param \AppBundle\Entity\Vesel $vesel
*
* #return VesselMoveStatus
*/
public function setVesel(\AppBundle\Entity\Vesel $vesel = null)
{
$this->vesel = $vesel;
return $this;
}
/**
* Get vesel
*
* #return \AppBundle\Entity\Vesel
*/
public function getVesel()
{
return $this->vesel;
}
/**
* Sometimes a GPS Coordinate may have the following format:
* 1,234532 if inserted as is then itn WONT be retreived correctly.
* Please use this method to sanitize the gps coordinate on setter method.
*
* #param string | float $coordinate
* #return number
*/
private function sanitizeGpsCoordinate($coordinate)
{
if(is_string($coordinate))
{
$coordinate=str_replace(',','.',$coordinate);
}
return (float)$coordinate;
}
}
The way you want to transform the data is not standard thus there is nothing generic in Doctrine to do so. But it's still very simple to achieve the objective you want.
However, IMHO the simplest solution is to use a closure to transform the result:
$result = $query->getResult();
$formatter = function($row) {
return [
"mmsi" => $row['mmsi']
"points" => [
"longtitude" => $row['logtitude'],
"latitude" => $row['latitude'],
"time" => $row['timestamp']
]
];
};
return array_map($formatter, $result);
The final array will have one element per point (veselMoveStatuses). If what you actually want is to have one element per vesel, consider changing the SELECT and adapt the formatter accordingly.
->select('v,m')
The result will be an array of Vesel objects with the veselMoveStatuses association already loaded (see this doc - section "Retrieve a CmsUser and fetch join all the phonenumbers he has").

Symfony Doctrine entity relations returns null data on saving

I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;

Symfony Doctrine2 Doesn't insert an available ID

I have a new problem related to Doctrine2 and Oracle...
I migrated an application from Symfony1 to symfony2. When I insert a new entry in the production database with Doctrine2, I get the error "ORA-00001: unique constraint violated". It tries to insert with the ID 1, if I try again it tries to insert with ID 2 etc...
Here is how I setup my entity :
<?php
namespace EspaceApprenti\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ApprenticeMark
*
* #ORM\Table(name="APPRENTICE_MARK", indexes={#ORM\Index(name="IDX_8582BCF7105754FC", columns={"FK_BRANCH"}), #ORM\Index(name="IDX_8582BCF7C9387C17", columns={"FK_YEAR"}), #ORM\Index(name="IDX_8582BCF73B451C64", columns={"FK_MARKTYPE"})})
* #ORM\Entity(repositoryClass="EspaceApprenti\UserBundle\Entity\ApprenticeMarkRepository")
*/
class ApprenticeMark
{
/**
* #var integer
*
* #ORM\Column(name="COEFFICIENT", type="bigint", nullable=false)
*/
private $coefficient;
/**
* #var integer
*
* #ORM\Column(name="ID", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="RESULT", type="decimal", precision=2, scale=1, nullable=false)
*/
private $result;
/**
* #var \ApprenticeBranch
*
* #ORM\ManyToOne(targetEntity="ApprenticeBranch")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_BRANCH", referencedColumnName="ID")
* })
*/
private $fkBranch;
/**
* #var \ApprenticeYear
*
* #ORM\ManyToOne(targetEntity="ApprenticeYear")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_YEAR", referencedColumnName="ID", onDelete="CASCADE")
* })
*/
private $fkYear;
/**
* #var \ApprenticeMarktype
*
* #ORM\ManyToOne(targetEntity="ApprenticeMarktype")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_MARKTYPE", referencedColumnName="ID")
* })
*/
private $fkMarktype;
/**
* Set coefficient
*
* #param integer $coefficient
* #return ApprenticeMark
*/
public function setCoefficient($coefficient)
{
$this->coefficient = $coefficient;
return $this;
}
/**
* Get coefficient
*
* #return integer
*/
public function getCoefficient()
{
return $this->coefficient;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set result
*
* #param integer $result
* #return ApprenticeMark
*/
public function setResult($result)
{
$this->result = $result;
return $this;
}
/**
* Get result
*
* #return integer
*/
public function getResult()
{
return $this->result;
}
/**
* Set fkBranch
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeBranch $fkBranch
* #return ApprenticeMark
*/
public function setFkBranch(\EspaceApprenti\UserBundle\Entity\ApprenticeBranch $fkBranch = null)
{
$this->fkBranch = $fkBranch;
return $this;
}
/**
* Get fkBranch
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeBranch
*/
public function getFkBranch()
{
return $this->fkBranch;
}
/**
* Set fkYear
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeYear $fkYear
* #return ApprenticeMark
*/
public function setFkYear(\EspaceApprenti\UserBundle\Entity\ApprenticeYear $fkYear = null)
{
$this->fkYear = $fkYear;
return $this;
}
/**
* Get fkYear
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeYear
*/
public function getFkYear()
{
return $this->fkYear;
}
/**
* Set fkMarktype
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeMarktype $fkMarktype
* #return ApprenticeMark
*/
public function setFkMarktype(\EspaceApprenti\UserBundle\Entity\ApprenticeMarktype $fkMarktype = null)
{
$this->fkMarktype = $fkMarktype;
return $this;
}
/**
* Get fkMarktype
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeMarktype
*/
public function getFkMarktype()
{
return $this->fkMarktype;
}
}
Here is the code of the controller :
public function newAction($idYear,$idYeartype)
{
$m = $this->getDoctrine()
->getManager();
// Get year
$year = $m->getRepository('EspaceApprentiUserBundle:ApprenticeYear')->find($idYear);
if (!$year) {
throw $this->createNotFoundException('Year not found');
}
// Get yeartype
$yeartype = $m->getRepository('EspaceApprentiUserBundle:ApprenticeYeartype')->find($idYeartype);
if (!$yeartype) {
throw $this->createNotFoundException('Year type not found');
}
// Get apprentice
$apprentice = $m->getRepository('EspaceApprentiUserBundle:ApprenticeApprentice')->find($year->getFkApprentice()->getId());
if (!$apprentice) {
throw $this->createNotFoundException('Apprentice type not found');
}
$mark = new ApprenticeMark();
$mark->setFkYear($year);
$form = $this->createForm(new ApprenticeMarkType($yeartype), $mark);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$m->persist($mark);
$m->flush();
return $this->redirect($this->generateUrl('grids_apprentice_index',array('idApprentice' => $apprentice->getId())));
}
}
return $this->render('EspaceApprentiGridsBundle:Grids_Mark:new.html.twig', array('apprentice' => $apprentice, 'form' => $form->createView()));
}
How do I configure Doctrine2 to get the last ID and not just increment from 1 ?
Or should I get and insert the last ID manually ?
Regards
I found the solution to my problem. Apparently my SEQUENCES in Oracle were not up to date, so I had to manually update them.

Symfony2 - Doctrine exception: class used in the discriminator map does not exist

I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.

Categories