Doctrine - Integrity Constraint Violation logic - symfony

I've been reviewing the Integrity constraint violation issues here on Stackoverflow for the past few days trying to resolve this issue, but I'm not having any success deducing the proper doctrine logic.
I have two entities that express a one-to-many and one-to-many relationship, but when I try to add and persist an item I get a insert error:
(in controller)
$user = $this->get('security.token_storage')->getToken()->getUser();
$chartnew = $Charts->setChartNo(9999);
$user->addUserschart($chartnew);
$em->persist($user);
$em->flush();
an exception occurred while executing 'INSERT INTO charts (chart_no, id_user) VALUES (?, ?)' with params [9999, null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id_user' cannot be null
class Users implements UserInterface
{
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Charts",cascade={"persist"}, mappedBy="charts")
*/
private $userscharts;
public function __construct()
{
$this->userscharts = new ArrayCollection();
//parent::__construct();
}
/**
* Add userschart
*
* #param \AppBundle\Entity\Charts $userschart
*
* #return Users
*/
public function addUserschart(\AppBundle\Entity\Charts $userschart)
{
$this->userscharts->add($userschart);
return $this;
}
.......
}
class Charts
{
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Users", inversedBy="userscharts")
* #ORM\JoinColumn(name="id_user", referencedColumnName="id_user")
*/
private $charts;
/**
* #var integer
*
* #ORM\Column(name="chart_no", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $chartNo;
/**
* #var integer
*
* #ORM\Column(name="id_user", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $idUser;
/**
* Set chartNo
*
* #param integer $chartNo
*
* #return Charts
*/
public function setChartNo($chartNo)
{
$this->chartNo = $chartNo;
return $this;
}
/**
* Get chartNo
*
* #return integer
*/
public function getChartNo()
{
return $this->chartNo;
}
/**
* Set idUser
*
* #param integer $idUser
*
* #return Charts
*/
public function setIdUser($idUser)
{
$this->idUser = $idUser;
return $this;
}
/**
* Get idUser
*
* #return integer
*/
public function getIdUser()
{
return $this->idUser;
}
/**
* Set charts
*
* #param \AppBundle\Entity\Users $charts
*
* #return Charts
*/
public function setCharts(\AppBundle\Entity\Users $charts = null)
{
$this->charts = $charts;
return $this;
}
/**
* Get charts
*
* #return \AppBundle\Entity\Users
*/
public function getCharts()
{
return $this->charts;
}
}

Related

Symfony2 Doctrine duplicate primary key

For one of my entities I can suddenly not add records to a specific table. The insert statement is ok, the problem is in the primary key, and that should be handled entirely by doctrine, I have no code to meddle with that. So I am at a loss as to what is actually happening here...
Is this a known effect of something other, PHP/db versions etc.?
... code for setting values of $extraOpening's properties ...
$em = $this->getDoctrine()->getManager();
$em->persist($extraOpening);
$em->flush($extraOpening);
[2017-09-18 11:05:47] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\UniqueConstraintViolationException: "An exception occurred while executing 'INSERT INTO extra_opening (open, close, arrOrDep, callsign, reason, additional, separateOpening, comment, price, debit_period) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["2017-09-08 10:50:00", "2017-09-08 10:50:00", "Ospec.", null, "mw test", null, 1, null, 1034, 117]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'"
--- UPDATE 2 ---
Adding my entity (the little update I just posted was wrong, so disregard if you had time to read it...).
I moved DB using phpmyadmin export and the same tool for import. Perhaps I did a setting wrong relating to relations or pKeys, but I've done it a hundred times and did nothing out of the defaults...
namespace ExtraOpeningBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ExtraOpening
*
* #ORM\Table(name="extra_opening")
* #ORM\Entity(repositoryClass="ExtraOpeningBundle\Repository\ExtraOpeningRepository")
*/
class ExtraOpening
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="open", type="datetime")
*/
private $open;
/**
* #var \DateTime
*
* #ORM\Column(name="close", type="datetime")
*/
private $close;
/**
* #var string
*
* #ORM\Column(name="arrOrDep", type="string", length=6, nullable=true)
*/
private $arrOrDep;
/**
* #var string
*
* #ORM\Column(name="callsign", type="string", length=30, nullable=true)
*/
private $callsign;
/**
* #var string
*
* #ORM\Column(name="reason", type="string", length=255, nullable=true)
*/
private $reason;
/**
* #var int
*
* #ORM\Column(name="additional", type="integer", nullable=true)
*/
private $additional;
/**
* #var bool
*
* #ORM\Column(name="separateOpening", type="boolean")
*/
private $separateOpening;
/**
* #var string
*
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #var int
*
* #ORM\Column(name="price", type="integer", nullable=true)
*/
private $price;
/**
* #var object \ExtraOpeningBundle\Entity\DebitPeriod
*
* #ORM\ManyToOne(targetEntity="\ExtraOpeningBundle\Entity\DebitPeriod", inversedBy="extraOpenings")
* #ORM\JoinColumn(name="debit_period", referencedColumnName="id", nullable=false)
*/
protected $debitPeriod;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set open
*
* #param \DateTime $open
*
* #return ExtraOpening
*/
public function setOpen($open)
{
$this->open = $open;
return $this;
}
/**
* Get open
*
* #return \DateTime
*/
public function getOpen()
{
return $this->open;
}
/**
* Set close
*
* #param \DateTime $close
*
* #return ExtraOpening
*/
public function setClose($close)
{
$this->close = $close;
return $this;
}
/**
* Get close
*
* #return \DateTime
*/
public function getClose()
{
return $this->close;
}
/**
* Set arrOrDep
*
* #param string $arrOrDep
*
* #return ExtraOpening
*/
public function setArrOrDep($arrOrDep)
{
$this->arrOrDep = $arrOrDep;
return $this;
}
/**
* Get arrOrDep
*
* #return string
*/
public function getArrOrDep()
{
return $this->arrOrDep;
}
/**
* Set callsign
*
* #param string $callsign
*
* #return ExtraOpening
*/
public function setCallsign($callsign)
{
$this->callsign = $callsign;
return $this;
}
/**
* Get callsign
*
* #return string
*/
public function getCallsign()
{
return $this->callsign;
}
/**
* Set reason
*
* #param string $reason
*
* #return ExtraOpening
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
/**
* Get reason
*
* #return string
*/
public function getReason()
{
return $this->reason;
}
/**
* Set additional
*
* #param integer $additional
*
* #return ExtraOpening
*/
public function setAdditional($additional)
{
$this->additional = $additional;
return $this;
}
/**
* Get additional
*
* #return int
*/
public function getAdditional()
{
return $this->additional;
}
/**
* Set separateOpening
*
* #param boolean $separateOpening
*
* #return ExtraOpening
*/
public function setSeparateOpening($separateOpening)
{
$this->separateOpening = $separateOpening;
return $this;
}
/**
* Get separateOpening
*
* #return bool
*/
public function getSeparateOpening()
{
return $this->separateOpening;
}
/**
* Set price
*
* #param integer $price
*
* #return ExtraOpening
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return int
*/
public function getPrice()
{
return $this->price;
}
/**
* Get debitTime
*
* #return string
*/
public function getDebitTime()
{
$open = $this->getOpen();
$close = $this->getClose();
$interval = date_diff($open, $close);
$r = $interval->format('%H:%I');
return $r;
}
/**
* Get debitTimeSeconds
*
* #return int
*/
public function getDebitTimeSeconds()
{
$open = $this->getOpen();
$close = $this->getClose();
$r = $close->format('U') - $open->format('U');
return $r;
}
/**
* Get debitHours
*
* #return decimal
*/
public function getDebitHours()
{
$open = $this->getOpen();
$close = $this->getClose();
$seconds = date_timestamp_get($close) - date_timestamp_get($open);
$hours = $seconds / 3600;
if($this->getSeparateOpening() && $hours < 3) {
$hours = 3;
}
return number_format($hours,2);
}
/**
* Get debitAmount
*
* #return decimal
*/
public function getDebitAmount()
{
$hours = $this->getDebitHours();
$price = $this->getPrice();
$amount = $hours * $price;
//return number_format($amount,2);
return $amount;
}
/**
* Set comment
*
* #param string $comment
*
* #return ExtraOpening
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Get acrGroup
*
* #return \HazardlogBundle\Entity\ACRGroup
*/
public function getAcrGroup()
{
return $this->getDebitPeriod()->getACRGroup();
}
/**
* Set debitPeriod
*
* #param \ExtraOpeningBundle\Entity\DebitPeriod $debitPeriod
*
* #return ExtraOpening
*/
public function setDebitPeriod(\ExtraOpeningBundle\Entity\DebitPeriod $debitPeriod)
{
$this->debitPeriod = $debitPeriod;
return $this;
}
/**
* Get debitPeriod
*
* #return \ExtraOpeningBundle\Entity\DebitPeriod
*/
public function getDebitPeriod()
{
return $this->debitPeriod;
}
}
As m-khalid-junaid https://stackoverflow.com/users/853360/m-khalid-junaid pointed out, the import had been corrupt and the auto_increment property had gone unnoticed, it was not set. Thank you.

How to get a sum of child object values in main entity by default

I have a PurchaseOrder entity and I have a Payments entity. Inside of the PurchaseOrder entity I'm trying to get the sum of Payments.amountPaid however it doesn't work as expected. Ideally the $allPaid should have a sum of all payments amountPaid for each PurchaseOrder. I was following this tutorial: enter link description here
Here is my PurchaseOrder entity:
class PurchaseOrder
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="RequestForEstimate", fetch="EAGER")
* #ORM\JoinColumn(name="request_id", referencedColumnName="request_id")
*/
private $request;
/**
* #ORM\OneToMany(targetEntity="Payment", mappedBy="purchaseOrder", orphanRemoval=true, cascade={"persist"}, fetch="EAGER")
*/
private $payments;
/**
* #var \DateTime
*
* #ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="update_time", type="datetime")
*/
private $updateTime;
/**
* #ORM\ManyToOne(targetEntity="PurchaseOrderStatus", cascade={"persist"})
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="ship_date",type="datetime")
*/
private $shipDate;
private $allPaid = 0;
public function getAllPaid()
{
foreach ($this->payments as $payment) {
$this->allPaid += $payment->amountPaid();
}
return $this->allPaid;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return PurchaseOrder
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return PurchaseOrder
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
/**
* Set status
*
* #param integer $status
*
* #return PurchaseOrder
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set shipDate
*
* #param \DateTime $shipDate
*
* #return PurchaseOrder
*/
public function setShipDate($shipDate)
{
$this->shipDate = $shipDate;
return $this;
}
/**
* Get shipDate
*
* #return \DateTime
*/
public function getShipDate()
{
return $this->shipDate;
}
/**
* Set requestForEstimate
*
* #param \InboundBundle\Entity\RequestForEstimate $requestForEstimate
*
* #return PurchaseOrder
*/
public function setRequestForEstimate(\InboundBundle\Entity\RequestForEstimate $requestForEstimate = null)
{
$this->requestForEstimate = $requestForEstimate;
return $this;
}
/**
* Get requestForEstimate
*
* #return \InboundBundle\Entity\RequestForEstimate
*/
public function getRequestForEstimate()
{
return $this->requestForEstimate;
}
/**
* Set requestId
*
* #param \InboundBundle\Entity\RequestForEstimate $requestId
*
* #return PurchaseOrder
*/
// public function setRequest(\InboundBundle\Entity\RequestForEstimate $request = null)
// {
// $this->request = $request;
// $request->setRequestId($this);
// return $this;
// }
public function setPayments(Payment $payments = null)
{
$this->payments = $payments;
return $this;
}
/**
* Get requestId
*
* #return \InboundBundle\Entity\RequestForEstimate
*/
public function getRequest()
{
return $this->request;
}
/**
* Set request
*
* #param \InboundBundle\Entity\RequestForEstimate $request
*
* #return PurchaseOrder
*/
/**
* Constructor
*/
public function __construct()
{
$this->payments = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add payment
*
* #param \InboundBundle\Entity\Payment $payment
*
* #return PurchaseOrder
*/
public function addPayment(\InboundBundle\Entity\Payment $payment)
{
$this->payments[] = $payment;
return $this;
}
/**
* Remove payment
*
* #param \InboundBundle\Entity\Payment $payment
*/
public function removePayment(\InboundBundle\Entity\Payment $payment)
{
$this->payments->removeElement($payment);
}
/**
* Get payments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPayments()
{
return $this->payments;
}
/**
* Set request
*
* #param \InboundBundle\Entity\RequestForEstimate $request
*
* #return PurchaseOrder
*/
public function setRequest(\InboundBundle\Entity\RequestForEstimate $request = null)
{
$this->request = $request;
return $this;
}
}
Payment entity:
class Payment
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="PurchaseOrder", inversedBy="payments", cascade={"persist", "detach"})
* #ORM\JoinColumn(name="purchase_order", referencedColumnName="id")
*/
private $purchaseOrder;
/**
* #var \DateTime
*
* #ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="update_time", type="datetime")
*/
private $updateTime;
/**
* #var int
*
* #ORM\Column(name="creator", type="integer")
*/
private $creator;
/**
* #var string
*
* #ORM\Column(name="amount_paid", type="decimal", precision=10, scale=2)
*/
private $amountPaid;
/**
* #ORM\ManyToOne(targetEntity="PaymentType", cascade={"persist"})
* #ORM\JoinColumn(name="payment_type", referencedColumnName="id")
*/
private $paymentType;
/**
* #var string
*
* #ORM\Column(name="external_transaction_id", type="string", length=255)
*/
private $externalTransactionId;
/**
* #var string
*
* #ORM\Column(name="including_fees", type="decimal", precision=10, scale=2)
*/
private $includingFees;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return Payment
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return Payment
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
/**
* Set creator
*
* #param integer $creator
*
* #return Payment
*/
public function setCreator($creator)
{
$this->creator = $creator;
return $this;
}
/**
* Get creator
*
* #return integer
*/
public function getCreator()
{
return $this->creator;
}
/**
* Set amountPaid
*
* #param string $amountPaid
*
* #return Payment
*/
public function setAmountPaid($amountPaid)
{
$this->amountPaid = $amountPaid;
return $this;
}
/**
* Get amountPaid
*
* #return string
*/
public function getAmountPaid()
{
return $this->amountPaid;
}
/**
* Set paymentType
*
* #param string $paymentType
*
* #return Payment
*/
public function setPaymentType($paymentType)
{
$this->paymentType = $paymentType;
return $this;
}
/**
* Get paymentType
*
* #return string
*/
public function getPaymentType()
{
return $this->paymentType;
}
/**
* Set externalTransactionId
*
* #param string $externalTransactionId
*
* #return Payment
*/
public function setExternalTransactionId($externalTransactionId)
{
$this->externalTransactionId = $externalTransactionId;
return $this;
}
/**
* Get externalTransactionId
*
* #return string
*/
public function getExternalTransactionId()
{
return $this->externalTransactionId;
}
/**
* Set includingFees
*
* #param string $includingFees
*
* #return Payment
*/
public function setIncludingFees($includingFees)
{
$this->includingFees = $includingFees;
return $this;
}
/**
* Get includingFees
*
* #return string
*/
public function getIncludingFees()
{
return $this->includingFees;
}
/**
* Set purchaseOrder
*
* #param \InboundBundle\Entity\PurchaseOrder $purchaseOrder
*
* #return Payment
*/
public function setPurchaseOrder(\InboundBundle\Entity\PurchaseOrder $purchaseOrder = null)
{
$this->purchaseOrder = $purchaseOrder;
return $this;
}
/**
* Get purchaseOrder
*
* #return \InboundBundle\Entity\PurchaseOrder
*/
public function getPurchaseOrder()
{
return $this->purchaseOrder;
}
}
When I dump the object it shows that the allPaid is 0 as set by default:
Matko's answer works, but your question makes implies that you're (or at least you were) missing something fundamental.
In your original code, the internal (private) allPaid property is initialized to zero. Your getAllPaid() method computes the actual value and returns it. As written, getAllPaid() will iterate over the payments collection every time it's invoked.
When you dump your entity, the $allPaid property is zero because you're dumping before getAllPaid() was invoked. If you call getAllPaid() and then dump, you'll see it contains the computed value. That is because getAllPaid() sets that value along the way. Or, instead of dumping (and seeing the uninitialized internal value), test by actually invoking getAllPaid() and see that the correct value is returned.
The weakness with Matko's solution is that it eagerly loads the collection every time. It's likely that there are some scenarios where you need to load a PurchaseOrder without loading all the payments.
Since $allPaid is private, you'll always be using getAllPaid() to access the value.
To improve your code, I would you memoize $allPaid
Initialize private $allPaid = null;. The semantics of null are more appropriate, because upon initialization, the value is not zero. It's unknown.
In getAllPaid(), add a check that $this->allPaid !== null, and if so, return early. That way, repeated calls to getAllPaid() don't recompute the value each time.
Be sure to clear the memo when the payments collection changes. PurchaseOrder::addPayment() and PurchaseOrder::removePayment() should both set $this->allPaid to null, forcing the value to be recomputed on the next time getAllPaid() is invoked.
Finally, remove the eager fetchmode on PurchaseOrder::payments. If you want to eagerly load them in cases where you know you'll need them, you can fetch-join them in your query.
You should use Doctrine2 postLoad event. The postLoad event occurs for an entity after the entity has been loaded into the current EntityManager from the database or after the refresh operation has been applied to it.
...
use Doctrine\ORM\Mapping as ORM;
...
/**
* ...
* #ORM\HasLifecycleCallbacks
* ...
*/
class PurchaseOrder
{
...
private $allPaid = null;
/**
* #ORM\PostLoad
*/
public function getAllPaid()
{
if (null === $this->allPaid) {
foreach ($this->payments as $payment) {
$this->allPaid += $payment->amountPaid();
}
}
return $this->allPaid;
}
}

Many to One Unidirectional relation in symfony2 has "No Association error"

I am trying to create a many to one unidirectional relationship between two tables. dateTime and availibilityList are two entities, one list may have multiple date and time.
I added the annotations likewise in the entity dateTime but it is showing me this error:
{
code: 500
message: "[Semantical Error] line 0, col 84 near 'd WHERE d.offerAvailibilityId': Error: Class StreetBumb\ApiBundle\Entity\availibilityList has no association named dateTime"
}
I updated my schema from the terminal by using this:
sudo php app/console doctrine:schema:update --force
It says : your database is already in sync with the current entity metadata.
dateTime Entity:
<?php
namespace StreetBumb\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* dateTime
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="StreetBumb\ApiBundle\Entity\dateTimeRepository")
*/
class dateTime
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="startDate", type="date")
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="endDate", type="date")
*/
private $endDate;
/**
* #var \DateTime
*
* #ORM\Column(name="startTime", type="time")
*/
private $startTime;
/**
* #var \DateTime
*
* #ORM\Column(name="endTime", type="time")
*/
private $endTime;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=55)
*/
private $type;
/**
* #var DateTime $offerAvailibilityId
*
* #ORM\ManyToOne(targetEntity="AvailibilityList")
* #ORM\JoinColumn(name="offerAvailibilityId", referencedColumnName="id")
*/
private $offerAvailibilityId;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set startDate
*
* #param \DateTime $startDate
* #return dateTime
*/
public function setStartDate($startDate)
{
$this->startDate = $startDate;
return $this;
}
/**
* Get startDate
*
* #return \DateTime
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* Set endDate
*
* #param \DateTime $endDate
* #return dateTime
*/
public function setEndDate($endDate)
{
$this->endDate = $endDate;
return $this;
}
/**
* Get endDate
*
* #return \DateTime
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* Set startTime
*
* #param \DateTime $startTime
* #return dateTime
*/
public function setStartTime($startTime)
{
$this->startTime = $startTime;
return $this;
}
/**
* Get startTime
*
* #return \DateTime
*/
public function getStartTime()
{
return $this->startTime;
}
/**
* Set endTime
*
* #param \DateTime $endTime
* #return dateTime
*/
public function setEndTime($endTime)
{
$this->endTime = $endTime;
return $this;
}
/**
* Get endTime
*
* #return \DateTime
*/
public function getEndTime()
{
return $this->endTime;
}
/**
* Set type
*
* #param string $type
* #return dateTime
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set offerAvailibilityId
*
* #param integer $offerAvailibilityId
* #return dateTime
*/
public function setOfferAvailibilityId($offerAvailibilityId)
{
$this->offerAvailibilityId = $offerAvailibilityId;
return $this;
}
/**
* Get offerAvailibilityId
*
* #return integer
*/
public function getOfferAvailibilityId()
{
return $this->offerAvailibilityId;
}
}
The function in repository i am calling in controller.
public function findOpeningDetailById($id)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('list')
->from('StreetBumbApiBundle:availibilityList', 'list')
->innerJoin('list.dateTime', 'd')
->where('d.offerAvailibilityId = :id')->setParameter('id', $id) //This line is showing error
->getQuery()->getResult();
return $qb;
}
Is there any problem in my join query or the relation i made(Many to one) is incorrect?
Please guide..
Thank you

Symfony 2/Doctrine - set value of forgein key

I had a problem like here. I followed the instructions of given solutions, but it generate another problem.
I've got two Entities:
namespace Acme\TyperBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Mecz
*
* #ORM\Table()
* #ORM\Entity
*/
class Mecz
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="druzyna1", type="string", length=255)
*/
private $druzyna1;
/**
* #var string
*
* #ORM\Column(name="druzyna2", type="string", length=255)
*/
private $druzyna2;
/**
* #var int
*
* #ORM\Column(name="bramki1", type="integer")
*/
private $bramki1;
/**
* #var int
*
* #ORM\Column(name="bramki2", type="integer")
*/
private $bramki2;
/**
* #var string
*
* #ORM\Column(name="wyniktyp", type="string", length=2)
*/
private $wyniktyp;
/**
* #var \DateTime
*
* #ORM\Column(name="data", type="datetime")
*/
private $data;
/**
* #var int
*
* #ORM\Column(name="typ1", type="float")
*/
private $typ1;
/**
* #var int
*
* #ORM\Column(name="typ1x", type="float")
*/
private $typ1x;
/**
* #var int
*
* #ORM\Column(name="typ2", type="float")
*/
private $typ2;
/**
* #var int
*
* #ORM\Column(name="typ2x", type="float")
*/
private $typ2x;
/**
* #var int
*
* #ORM\Column(name="typx", type="float")
*/
private $typx;
/**
* #ORM\OneToMany(targetEntity="Typy", mappedBy="meczid")
*/
protected $meczid;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set druzyna1
*
* #param string $druzyna1
* #return Mecz
*/
public function setDruzyna1($druzyna1)
{
$this->druzyna1 = $druzyna1;
return $this;
}
/**
* Get druzyna1
*
* #return string
*/
public function getDruzyna1()
{
return $this->druzyna1;
}
/**
* Set druzyna2
*
* #param string $druzyna2
* #return Mecz
*/
public function setDruzyna2($druzyna2)
{
$this->druzyna2 = $druzyna2;
return $this;
}
/**
* Get druzyna2
*
* #return string
*/
public function getDruzyna2()
{
return $this->druzyna2;
}
/**
* Set bramki1
*
* #param integer $bramki1
* #return Mecz
*/
public function setBramki1($bramki1)
{
$this->bramki1 = $bramki1;
return $this;
}
/**
* Get bramki1
*
* #return integer
*/
public function getBramki1()
{
return $this->bramki1;
}
/**
* Set bramki2
*
* #param integer $bramki2
* #return Mecz
*/
public function setBramki2($bramki2)
{
$this->bramki2 = $bramki2;
return $this;
}
/**
* Get bramki2
*
* #return integer
*/
public function getBramki2()
{
return $this->bramki2;
}
/**
* Set wyniktyp
*
* #param string $wyniktyp
* #return Mecz
*/
public function setWyniktyp($wyniktyp)
{
$this->wyniktyp = $wyniktyp;
return $this;
}
/**
* Get wyniktyp
*
* #return string
*/
public function getWyniktyp()
{
return $this->wyniktyp;
}
/**
* Set data
*
* #param \DateTime $data
* #return Mecz
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return \DateTime
*/
public function getData()
{
return $this->data;
}
/**
* Set typ1
*
* #param float $typ1
* #return Mecz
*/
public function setTyp1($typ1)
{
$this->typ1 = $typ1;
return $this;
}
/**
* Get typ1
*
* #return float
*/
public function getTyp1()
{
return $this->typ1;
}
/**
* Set typ2
*
* #param float $typ2
* #return Mecz
*/
public function setTyp2($typ2)
{
$this->typ2 = $typ2;
return $this;
}
/**
* Get typ2
*
* #return float
*/
public function getTyp2()
{
return $this->typ2;
}
/**
* Set typ1x
*
* #param float $typ1x
* #return Mecz
*/
public function setTyp1x($typ1x)
{
$this->typ1x = $typ1x;
return $this;
}
/**
* Get typ1x
*
* #return float
*/
public function getTyp1x()
{
return $this->typ1x;
}
/**
* Set typ2x
*
* #param float $typ2x
* #return Mecz
*/
public function setTyp2x($typ2x)
{
$this->typ2x = $typ2x;
return $this;
}
/**
* Get typ2x
*
* #return float
*/
public function getTyp2x()
{
return $this->typ2x;
}
/**
* Set typx
*
* #param float $typx
* #return Mecz
*/
public function setTypx($typx)
{
$this->typx = $typx;
return $this;
}
/**
* Get typx
*
* #return float
*/
public function getTypx()
{
return $this->typx;
}
/**
* Set id
*
* #param integer $id
* #return Mecz
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Add meczid
*
* #param \Acme\TyperBundle\Entity\Typy $meczid
* #return Mecz
*/
public function addMeczid(\Acme\TyperBundle\Entity\Typy $meczid)
{
$this->meczid[] = $meczid;
return $this;
}
/**
* Remove meczid
*
* #param \Acme\TyperBundle\Entity\Typy $meczid
*/
public function removeMeczid(\Acme\TyperBundle\Entity\Typy $meczid)
{
$this->meczid->removeElement($meczid);
}
/**
* Get meczid
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMeczid()
{
return $this->meczid;
}
/**
* Add mecz
*
* #param \Acme\TyperBundle\Entity\Typy $mecz
* #return Mecz
*/
public function addMecz(\Acme\TyperBundle\Entity\Typy $mecz)
{
$this->mecz[] = $mecz;
return $this;
}
/**
* Remove mecz
*
* #param \Acme\TyperBundle\Entity\Typy $mecz
*/
public function removeMecz(\Acme\TyperBundle\Entity\Typy $mecz)
{
$this->mecz->removeElement($mecz);
}
/**
* Get mecz
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMecz()
{
return $this->mecz;
}
/**
* Add mecztyp
*
* #param \Acme\TyperBundle\Entity\Typy $mecztyp
* #return Mecz
*/
public function addMecztyp(\Acme\TyperBundle\Entity\Typy $mecztyp)
{
$this->mecztyp[] = $mecztyp;
return $this;
}
/**
* Remove mecztyp
*
* #param \Acme\TyperBundle\Entity\Typy $mecztyp
*/
public function removeMecztyp(\Acme\TyperBundle\Entity\Typy $mecztyp)
{
$this->mecztyp->removeElement($mecztyp);
}
/**
* Get mecztyp
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMecztyp()
{
return $this->mecztyp;
}
}
and
namespace Acme\TyperBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Typy
*
* #ORM\Table()
* #ORM\Entity
*/
class Typy
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="id_kuponu", type="integer")
*/
private $id_kuponu;
/**
* #var integer
*
* #ORM\Column(name="id_meczu", type="integer")
*/
private $id_meczu;
/**
* #var string
*
* #ORM\Column(name="typ", type="string", length=2)
*/
private $typ;
/**
* #var int
*
* #ORM\Column(name="stawka", type="float")
*/
private $stawka;
/**
* #ORM\ManyToOne(targetEntity="Mecz", inversedBy="meczid",cascade={"persist"})
* #ORM\JoinColumn(name="id_meczu", referencedColumnName="id")
*/
private $meczid;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id_kuponu
*
* #param integer $idKuponu
* #return Typy
*/
public function setIdKuponu($idKuponu)
{
$this->id_kuponu = $idKuponu;
return $this;
}
/**
* Get id_kuponu
*
* #return integer
*/
public function getIdKuponu()
{
return $this->id_kuponu;
}
/**
* Set id_meczu
*
* #param integer $idMeczu
* #return Typy
*/
public function setIdMeczu($idMeczu)
{
$this->id_meczu = $idMeczu;
return $this;
}
/**
* Get id_meczu
*
* #return integer
*/
public function getIdMeczu()
{
return $this->id_meczu;
}
/**
* Set typ
*
* #param string $typ
* #return Typy
*/
public function setTyp($typ)
{
$this->typ = $typ;
return $this;
}
/**
* Get typ
*
* #return string
*/
public function getTyp()
{
return $this->typ;
}
/**
* Set meczid
*
* #param \Acme\TyperBundle\Entity\Mecz $meczid
* #return Typy
*/
public function setMeczid(\Acme\TyperBundle\Entity\Mecz $meczid = null)
{
$this->meczid = $meczid;
return $this;
}
/**
* Get meczid
*
* #return \Acme\TyperBundle\Entity\Mecz
*/
public function getMeczid()
{
return $this->meczid;
}
/**
* Set stawka
*
* #param float $stawka
* #return Typy
*/
public function setStawka($stawka)
{
$this->stawka = $stawka;
return $this;
}
/**
* Get stawka
*
* #return float
*/
public function getStawka()
{
return $this->stawka;
}
}
So I want to use this code to insert data to table:
$mecz = new Mecz();
$mecz->setId($id_meczu);
$typs = new Typy();
$et = $this->getDoctrine()->getManager();
$typs->setIdKuponu($id_kuponu);
$typs->setMeczid($mecz);
$typs->setTyp($typ);
$typs->setStawka($stawka);
$et->persist($typs);
$et->flush();
And i get exception:
An exception occurred while executing 'INSERT INTO Mecz (id, druzyna1, druzyna2, bramki1, bramki2, wyniktyp, data, typ1, typ1x, typ2, typ2x, typx) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["2", null, null, null, null, null, null, null, null, null, null, null]:
I don't know why, because i want to instert data to "Typy" table not "Mecz" table. Can anyone could help me?
The problem is the following:
You have the field Typy::meczid, but this field does (from the perspecitve of Doctrine) not hold a numeric ID, but a reference to a Mecz instance. Therefore the name meczid is misleading, it should be Typy::mecz. I'd recommend renaming the field and the accessors for the sake of consistency.
Now the Typy entity expects a Mecz entity to be set, which you do: You create a new Mecz(), and assign it to Typy with $typs->setMeczid($mecz);. BUT: The Mecz instance is lacking lots all properties except the ID. (By the way, in Doctrine IDs should generally be autogenerated, not by the business logic.) As the Typy entity depends on Mecz, the Mecz must be persisted first, so its reference can be stored with the Typy.
Bottom line: You must fill the generated Mecz with the missing properties.
Hint: To avoid that this type of error happens on the DB level, you should use Symfony's entity validation component. This will allow a much better error handling; both during development, and in production.

Symfony2, doctrine ManyToOne relationships error

I am trying to build a log of some action performed on some site using Symfony2 and Doctrine. I have 2 tables Sites and Logs. The Logs table will contain a siteid which is a foreign key to the id column of sites table. The Logs table can have multiple logs for same site.
When I try to insert an entry in the log table I get siteid is null error.
Here is my code:
Sites Entity:
<?php
namespace A\SHB\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sites
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="A\SHB\Entity\SitesRepository")
*/
class Sites
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="log", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="siteid")
* })
*/
private $siteLog;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Constructor
*/
public function __construct()
{
$this->siteLog = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add siteLog
*
* #param \A\SHB\Entity\SiteLog $siteLog
* #return Sites
*/
public function addSiteLog(\A\SHB\Entity\SiteLog $siteLog)
{
$this->siteLog[] = $siteLog;
return $this;
}
/**
* Remove siteLog
*
* #param \A\SHB\Entity\SiteLog $siteLog
*/
public function removeSiteLog(\A\SHB\Entity\SiteLog $siteLog)
{
$this->siteLog->removeElement($siteLog);
}
/**
* Get siteLog
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSiteLog()
{
return $this->siteLog;
}
}
Logs Entity:
<?php
namespace A\SHB\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Logs
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="A\SHB\Entity\LogsRepository")
*/
class Logs
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="siteid", type="integer")
*/
private $siteid;
/**
* #var integer
*
* #ORM\Column(name="dateline", type="integer")
*/
private $dateline;
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
* })
*/
private $log;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set siteid
*
* #param integer $siteid
* #return Logs
*/
public function setSiteid($siteid)
{
$this->siteid = $siteid;
return $this;
}
/**
* Get siteid
*
* #return integer
*/
public function getSiteid()
{
return $this->siteid;
}
/**
* Set dateline
*
* #param integer $dateline
* #return Logs
*/
public function setDateline($dateline)
{
$this->dateline = $dateline;
return $this;
}
/**
* Get dateline
*
* #return integer
*/
public function getDateline()
{
return $this->dateline;
}
/**
* Set log
*
* #param \A\SHB\Entity\Log $log
* #return Logs
*/
public function setLog(\A\SHB\Entity\Log $log = null)
{
$this->log = $log;
return $this;
}
/**
* Get log
*
* #return \A\SHB\Entity\Log
*/
public function getLog()
{
return $this->log;
}
}
Controller :
public function indexAction()
{
$sites = $this->getDoctrine()->getRepository('ASHB:Sites')->findAll();
foreach ($sites as $site)
{
$host = $site->getForum();
// Do something ....
$log = new Logs();
$log->setSiteid($site->getId());
$log->setDateline($temp['dateline']);
$em = $this->getDoctrine()->getManager();
$em->persist($log);
$em->flush();
}
return $this->render('ASHB:Default:index.html.twig', array('sites' => $output, 'counters' => $counters));
}
Now when I run this code, I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'siteid' cannot be null"
If I var_dump $log, before $em->persist($log);, the siteid is there. I am not sure what is wrong and why the siteid is getting set to null.
Update 1:
I tried to make the following changes and still get the same error:
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites", inversedBy="siteLog")
*/
private $log;
OneToMany doesn't need a JoinColumn. So it should look like, according to the documentation.
class Sites
{
/**
* #ORM\OneToMany(targetEntity="Logs", mappedBy="log")
*/
private $site_log;
}
class Logs
{
/**
* #ORM\ManyToOne(targetEntity="Sites", inversedBy="site_log")
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
*/
private $log;
}
orderBy and cascade were ignored for simplicity.
you have problem in your sturcture,
Remove this from Logs Entity
/**
* #var integer
*
* #ORM\Column(name="siteid", type="integer")
*/
private $siteid;
And then replace this part
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
* })
*/
private $log;
with
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites" inversedBy="logs")
*/
private $site;
And in your sites entity replace this with
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="logs", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="siteid")
* })
*/
private $logs;
with
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="site", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="id")
* })
*/
private $logs;
And then use proper setters and getters for these new feilds mean pass object to setter functions, for the class they are being mapped for(if you dont know this part write in comment i will do it as well)

Resources