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
Related
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;
}
}
BudgetItem is related as ManyToOne to Budget and to Product. Here are the 3 entities:
BudgetItem
<?php
namespace CDGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\Product;
/**
* BudgetItem
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\BudgetItemRepository")
* #ORM\HasLifecycleCallbacks
*/
class BudgetItem
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Product")
* #ORM\JoinColumn(nullable=false)
*/
private $product;
/**
* #var integer
*
* #ORM\Column(name="meters", type="integer")
*/
private $meters;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", scale=2)
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="Budget", inversedBy="items")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $budget;
/**
* To String
*
* #return string
*/
public function __toString()
{
return $this->getProduct()->getName();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set budget
*
* #param integer $budget
*
* #return BudgetItem
*/
public function setBudget(Budget $budget)
{
$this->budget = $budget;
return $this;
}
/**
* Get budget
*
* #return integer
*/
public function getBudget()
{
return $this->budget;
}
/**
* Set product
*
* #param integer $product
*
* #return BudgetItem
*/
public function setProduct(Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return integer
*/
public function getProduct()
{
return $this->product;
}
/**
* Set meters
*
* #param integer $meters
*
* #return BudgetItem
*/
public function setMeters($meters)
{
$this->meters = $meters;
return $this;
}
/**
* Get meters
*
* #return integer
*/
public function getMeters()
{
return $this->meters;
}
/**
* Set price
*
* #param string $price
*
* #return BudgetItem
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* #return integer;
*/
public function decreaseProductMeters()
{
return $this->getProduct()->getMeters() - $this->getMeters();
}
/**
* #ORM\PrePersist
*/
public function onPreEvents()
{
$this->getProduct()->setMeters($this->decreaseProductMeters());
}
public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityUpdates() as $entity) {
$entity->getProduct();
$em->persist($entity);
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
}
Budget
<?php
namespace CDGBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\Customer;
use CDGBundle\Entity\BudgetItem;
/**
* Budget
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\BudgetRepository")
* #ORM\HasLifecycleCallbacks
*/
class Budget
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="Customer", inversedBy="budgets")
*/
private $customer;
/**
* #var integer
*
* #ORM\OneToMany(targetEntity="BudgetItem", mappedBy="budget", cascade={"persist"})
*/
private $items;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var integer
*
* #ORM\Column(name="installment_rate", type="integer")
*/
private $installmentRate;
/**
* #var integer
*
* #ORM\Column(name="check_for", type="integer")
*/
private $checkFor;
/**
* #var \DateTime
*
* #ORM\Column(name="starts_at", type="datetime", nullable=true)
*/
private $startsAt;
/**
* #var \DateTime
*
* #ORM\Column(name="deadline", type="datetime", nullable=true)
*/
private $deadline;
/**
* #var string
*
* #ORM\Column(name="is_approved", type="string", length=1, nullable=true)
*/
private $isApproved;
/**
* #var string
*
* #ORM\Column(name="has_started", type="string", length=1, nullable=true)
*/
private $hasStarted;
/**
* #var decimal
*
* #ORM\Column(name="installment_rate_price", type="decimal", scale=2, nullable=true)
*/
private $installmentRatePrice;
/**
* #var decimal
*
* #ORM\Column(name="total_budget_price", type="decimal", scale=2, nullable=true)
*/
private $totalBudgetPrice;
/**
* #var \DateTime
*
* #ORM\Column(name="next_payment_date", type="datetime", nullable=true)
*/
private $nextPaymentDate;
/**
* #var string
*
* #ORM\Column(name="is_paid", type="string", length=1)
*/
private $isPaid;
/**
* #var string
*
* #ORM\Column(name="obs", type="text", nullable=true)
*/
private $obs;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Constructor
*/
public function __construct()
{
$this->items = new ArrayCollection();
$this->createdAt = new \DateTime();
$this->isPaid = 'n';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set address
*
* #param string $address
*
* #return Budget
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set installmentRate
*
* #param integer $installmentRate
*
* #return Budget
*/
public function setInstallmentRate($installmentRate)
{
$this->installmentRate = $installmentRate;
return $this;
}
/**
* Get installmentRate
*
* #return integer
*/
public function getInstallmentRate()
{
return $this->installmentRate;
}
/**
* Set checkFor
*
* #param integer $checkFor
*
* #return Budget
*/
public function setCheckFor($checkFor)
{
$this->checkFor = $checkFor;
return $this;
}
/**
* Get checkFor
*
* #return integer
*/
public function getCheckFor()
{
return $this->checkFor;
}
/**
* Set startsAt
*
* #param \DateTime $startsAt
*
* #return Budget
*/
public function setStartsAt($startsAt)
{
$this->startsAt = $startsAt;
return $this;
}
/**
* Get startsAt
*
* #return \DateTime
*/
public function getStartsAt()
{
return $this->startsAt;
}
/**
* Set deadline
*
* #param \DateTime $deadline
*
* #return Budget
*/
public function setDeadline($deadline)
{
$this->deadline = $deadline;
return $this;
}
/**
* Get deadline
*
* #return \DateTime
*/
public function getDeadline()
{
return $this->deadline;
}
/**
* Set isApproved
*
* #param string $isApproved
*
* #return Budget
*/
public function setIsApproved($isApproved)
{
$this->isApproved = $isApproved;
return $this;
}
/**
* Get isApproved
*
* #return string
*/
public function getIsApproved()
{
return $this->isApproved;
}
/**
* Set hasStarted
*
* #param string $hasStarted
*
* #return Budget
*/
public function setHasStarted($hasStarted)
{
$this->hasStarted = $hasStarted;
return $this;
}
/**
* Get hasStarted
*
* #return string
*/
public function getHasStarted()
{
return $this->hasStarted;
}
/**
* Set installmentRatePrice
*
* #param string $installmentRatePrice
*
* #return Budget
*/
public function setInstallmentRatePrice($installmentRatePrice)
{
$this->installmentRatePrice = $installmentRatePrice;
return $this;
}
/**
* Get installmentRatePrice
*
* #return string
*/
public function getInstallmentRatePrice()
{
return $this->installmentRatePrice;
}
/**
* Set totalBudgetPrice
*
* #param string $totalBudgetPrice
*
* #return Budget
*/
public function setTotalBudgetPrice($totalBudgetPrice)
{
$this->totalBudgetPrice = $totalBudgetPrice;
return $this;
}
/**
* Get totalBudgetPrice
*
* #return string
*/
public function getTotalBudgetPrice()
{
return $this->totalBudgetPrice;
}
/**
* Set nextPaymentDate
*
* #param \DateTime $nextPaymentDate
*
* #return Budget
*/
public function setNextPaymentDate($nextPaymentDate)
{
$this->nextPaymentDate = $nextPaymentDate;
return $this;
}
/**
* Get nextPaymentDate
*
* #return \DateTime
*/
public function getNextPaymentDate()
{
return $this->nextPaymentDate;
}
/**
* Set isPaid
*
* #param string $isPaid
*
* #return Budget
*/
public function setIsPaid($isPaid)
{
$this->isPaid = $isPaid;
return $this;
}
/**
* Get isPaid
*
* #return string
*/
public function getIsPaid()
{
return $this->isPaid;
}
/**
* Set obs
*
* #param string $obs
*
* #return Budget
*/
public function setObs($obs)
{
$this->obs = $obs;
return $this;
}
/**
* Get obs
*
* #return string
*/
public function getObs()
{
return $this->obs;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Budget
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set customer
*
* #param Customer $customer
*
* #return Budget
*/
public function setCustomer(Customer $customer = null)
{
$this->customer = $customer;
return $this;
}
/**
* Get customer
*
* #return Customer
*/
public function getCustomer()
{
return $this->customer;
}
/**
* Add item
*
* #param BudgetItem $item
*
* #return Budget
*/
public function addItem(BudgetItem $item)
{
$item->setBudget($this);
$this->items->add($item);
return $this;
}
/**
* Remove item
*
* #param BudgetItem $item
*/
public function removeItem(BudgetItem $item)
{
$this->items->removeElement($item);
}
/**
* Get items
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getItems()
{
return $this->items;
}
/**
* #return \DateTime
*/
public function generateNextPaymentDate()
{
if ($this->getStartsAt() !== null) {
$date = new \DateTime($this->getStartsAt()->format('Y-m-d'));
return $date->add(new \DateInterval('P' . $this->getCheckFor() . 'D'));
}
}
/**
* #return decimal
*/
public function calculateTotalBudgetPrice()
{
$totalBudgetPrice = 0;
foreach ($this->getItems() as $item) {
$totalBudgetPrice += $item->getPrice();
}
return $totalBudgetPrice;
}
/**
* #return decimal
*/
public function calculateInstallmentRatePrice()
{
return $this->calculateTotalBudgetPrice() / $this->getInstallmentRate();
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function onPreEvents()
{
$this->setNextPaymentDate($this->generateNextPaymentDate());
$this->setInstallmentRatePrice($this->calculateInstallmentRatePrice());
$this->setTotalBudgetPrice($this->calculateTotalBudgetPrice());
}
}
Product
<?php
namespace CDGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\ProductType;
/**
* Product
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\ProductRepository")
* #ORM\HasLifecycleCallbacks
*/
class Product
{
/**
* #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;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="ProductType")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", scale=2)
*/
private $price;
/**
* #var integer
*
* #ORM\Column(name="meters", type="integer", nullable=true)
*/
private $meters;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Constructor
*/
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* To String
*
* #return string
*/
public function __toString()
{
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set type
*
* #param \CDGBundle\Entity\ProductType $type
*
* #return Product
*/
public function setType(ProductType $type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return \CDGBundle\Entity\ProductType
*/
public function getType()
{
return $this->type;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set meters
*
* #param integer $meters
*
* #return Product
*/
public function setMeters($meters)
{
$this->meters = $meters;
return $this;
}
/**
* Get meters
*
* #return integer
*/
public function getMeters()
{
return $this->meters;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Product
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}
Product is a collection form inside of Budget. It lists all the registered products to choose when registering a new budget. I have all the necessary JavaScript and a macro to show the form.
I need to update the total amount of meters from Product entity when EDITING an existing Budget. I have an onFlush method inside of BudgetItem for this:
public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityUpdates() as $entity) {
$entity->getItems();
$em->persist($entity);
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
Now here is my problem. I do not know what to do inside of the foreach method. I need to do the same as I do in the PrePersist method, but I get different errors.
Inside of the loop, if I do $entity->getItems(), I get the error:
Attempted to call an undefined method named "getItems" of class "CDGBundle\Entity\BudgetItem".
If I do $entity->getProduct(), the error:
Attempted to call an undefined method named "getProduct" of class "CDGBundle\Entity\Budget".
Why does it magically change the entity? For God sake someone help me with this. Doctrine2 has a too complicated updating event.
In a Doctrine listener, you always need to check the class of the entity, since every single updated items are stored in your getScheduledEntityUpdates() method.
The solution is to test if updated entity is an instance of Budget:
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if ($entity instanceof Budget) {
// $entity is a Budget entity
// ... your code here
}
}
I have 3 tables: EdiTradingPartner, EdiDocType and EdiTradingPartnerTransactions
src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiTradingPartner
*
* #ORM\Table(name="edi_trading_partner")
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiTradingPartnerRepository")
*/
class EdiTradingPartner
{
/**
* #var string
*
* #ORM\Column(name="edi_interchange_id", type="string", length=30, nullable=false)
*/
private $ediInterchangeId;
/**
* #var string
*
* #ORM\Column(name="tp_name", type="string", length=30, nullable=false)
*/
private $tpName;
/**
* #var string
*
* #ORM\Column(name="tp_location", type="string", length=50, nullable=false)
*/
private $tpLocation;
/**
* #var integer
*
* #ORM\Column(name="edi_trading_partner_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediTradingPartnerId;
/**
* Set ediInterchangeId
*
* #param string $ediInterchangeId
* #return EdiTradingPartner
*/
public function setEdiInterchangeId($ediInterchangeId)
{
$this->ediInterchangeId = $ediInterchangeId;
return $this;
}
/**
* Get ediInterchangeId
*
* #return string
*/
public function getEdiInterchangeId()
{
return $this->ediInterchangeId;
}
/**
* Set tpName
*
* #param string $tpName
* #return EdiTradingPartner
*/
public function setTpName($tpName)
{
$this->tpName = $tpName;
return $this;
}
/**
* Get tpName
*
* #return string
*/
public function getTpName()
{
return $this->tpName;
}
/**
* Set tpLocation
*
* #param string $tpLocation
* #return EdiTradingPartner
*/
public function setTpLocation($tpLocation)
{
$this->tpLocation = $tpLocation;
return $this;
}
/**
* Get tpLocation
*
* #return string
*/
public function getTpLocation()
{
return $this->tpLocation;
}
/**
* Get ediTradingPartnerId
*
* #return integer
*/
public function getEdiTradingPartnerId()
{
return $this->ediTradingPartnerId;
}
}
src\Matrix\MatrixEdiBundle\Entity\EdiDocType
<?php
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiDocType
*
* #ORM\Table(name="edi_doc_type")
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiDocTypeRepository")
*/
class EdiDocType
{
/**
* #var integer
*
* #ORM\Column(name="doc_type", type="integer", nullable=false)
*/
private $docType;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="direction", type="string", length=10, nullable=false)
*/
private $direction;
/**
* #var integer
*
* #ORM\Column(name="edi_doc_type_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediDocTypeId;
/**
* Set docType
*
* #param integer $docType
* #return EdiDocType
*/
public function setDocType($docType)
{
$this->docType = $docType;
return $this;
}
/**
* Get docType
*
* #return integer
*/
public function getDocType()
{
return $this->docType;
}
/**
* Set name
*
* #param string $name
* #return EdiDocType
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return EdiDocType
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set direction
*
* #param string $direction
* #return EdiDocType
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return string
*/
public function getDirection()
{
return $this->direction;
}
/**
* Get ediDocTypeId
*
* #return integer
*/
public function getEdiDocTypeId()
{
return $this->ediDocTypeId;
}
}
src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiTradingPartnerTransactions
*
* #ORM\Table(name="edi_trading_partner_transactions", indexes={#ORM\Index(name="edi_tp_id", columns={"edi_tp_id", "edi_doc_type_id"}), #ORM\Index(name="edi_transactions_id", columns={"edi_doc_type_id"}), #ORM\Index(name="IDX_F2BE50F7B9C737A1", columns={"edi_tp_id"})})
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiTradingPartnerTransactionsRepository")
*/
class EdiTradingPartnerTransactions
{
/**
* #var integer
*
* #ORM\Column(name="edi_tp_transactions_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediTpTransactionsId;
/**
* #var \Matrix\MatrixEdiBundle\Entity\EdiDocType
*
* #ORM\ManyToOne(targetEntity="Matrix\MatrixEdiBundle\Entity\EdiDocType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="edi_doc_type_id", referencedColumnName="edi_doc_type_id")
* })
*/
private $ediDocType;
/**
* #var \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
*
* #ORM\ManyToOne(targetEntity="Matrix\MatrixEdiBundle\Entity\EdiTradingPartner")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="edi_tp_id", referencedColumnName="edi_trading_partner_id")
* })
*/
private $ediTp;
/**
* Get ediTpTransactionsId
*
* #return integer
*/
public function getEdiTpTransactionsId()
{
return $this->ediTpTransactionsId;
}
/**
* Set ediDocType
*
* #param \Matrix\MatrixEdiBundle\Entity\EdiDocType $ediDocType
* #return EdiTradingPartnerTransactions
*/
public function setEdiDocType(\Matrix\MatrixEdiBundle\Entity\EdiDocType $ediDocType = null)
{
$this->ediDocType = $ediDocType;
return $this;
}
/**
* Get ediDocType
*
* #return \Matrix\MatrixEdiBundle\Entity\EdiDocType
*/
public function getEdiDocType()
{
return $this->ediDocType;
}
/**
* Set ediTp
*
* #param \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner $ediTp
* #return EdiTradingPartnerTransactions
*/
public function setEdiTp(\Matrix\MatrixEdiBundle\Entity\EdiTradingPartner $ediTp = null)
{
$this->ediTp = $ediTp;
return $this;
}
/**
* Get ediTp
*
* #return \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
*/
public function getEdiTp()
{
return $this->ediTp;
}
}
I want to insert into EdiTradingPartnerTransactions table yet I really don't know what to do since I've been receiving this error:
Catchable fatal error: Argument 1 passed to
Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions::setEdiTp()
must be an instance of
Matrix\MatrixEdiBundle\Entity\EdiTradingPartner, string given, called
in
C:\xampp\htdocs\Editracker\src\Matrix\MatrixEdiBundle\Controller\MatrixController.php
on line 474 and defined in
C:\xampp\htdocs\Editracker\src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions.php
on line 85
Here's my function in the controller side:
public function deleteTpTransAction($tpId, $docType, $direction, $tpName) {
$em = $this->getDoctrine()->getManager();
$docTypeId = $em->getRepository('MatrixEdiBundle:EdiDocType')->getId($docType, $direction);
if ($docTypeId != null) {
$result = $em->getRepository('MatrixEdiBundle:EdiTradingPartnerTransactions')->getTpTrans($tpId, $docType, $direction);
if ($result == null) {
$transaction = new EdiTradingPartnerTransactions();
$transaction->setEdiTp($tpId);
$transaction->setEdiDocType($docTypeId);
$em->persist($transaction);
} else {
foreach ($result as $key) {
$id = $key->getEdiTpTransactionsId();
$transaction = $em->getRepository('MatrixEdiBundle:EdiTradingPartnerTransactions')->find($id);
$em->remove($transaction);
}
}
$em->flush();
}
return $this->redirect($this->generateUrl('matrix_edi_tpTrans'));
}
Any help would really be appreciated. Thanks in advanced!
The error here is pretty clear: Doctrine handle, at least for relationships, only objects of the "related" (let's call that way) entity.
When you do
$transaction->setEdiTp($tpId);
$transaction->setEdiDocType($docTypeId);
you're trying to insert ID(s) of related objects. This is an error: although your db expects an integer (foreign key), Doctrine is an abstaction "pillow" between your code and db; it choose to work with objects and not with ids(you can see it pretty clearly into entity classes files)
Solution here is pretty simple:
Fetch from db the entity for setEdiTp and setEdiDocType
Pass them to the functions
In PHP (Symfony):
$ediTp = $em
->getRepository('MatrixEdiBundle:EdiTp')
->findOneById($tpId);
$ediDocType = $em
->getRepository('MatrixEdiBundle:EdiDocType')
->findOneById($docTypeId);
then
$transaction->setEdiTp($ediTp);
$transaction->setEdiDocType($ediDocType);
Your error is because setEdiTp need an instance of EdiTradingPartner.
Your error say string given.
Because $tpId is string.
Verify
Change
$transaction->setEdiTp($tpId);
To
// $transaction->setEdiTp($tpId);
var_dump($tpId);
Normally, $tpId return a string, not a object.
So when you call deleteTpTransAction, $tpId must be an instance of setEdiTp
Changement :
$editp = $em->getRepository('MatrixEdiBundle:EdiTradingPartner')->find($tpId);
and change
$transaction->setEdiTp($tpId);
by
$transaction->setEdiTp($editTp);
I'm trying to add a simple comment entity, with the "postedOn" attribute as a Datetime. Whenever I try to add a comment, I get this error :
Error: Call to undefined method Symfony\Component\Validator\Constraints\DateTime::format() in /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php line 53
Any idea ?
Here's the entity code :
<?php
namespace AOFVH\FlyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Comment
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AOFVH\FlyBundle\Entity\CommentRepository")
*/
class Comment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="rating", type="integer")
*/
private $rating;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $postedon;
/**
* #var string
*
* #ORM\Column(name="text", type="text")
*/
private $text;
/**
* #var $commenter
*
* #ORM\ManyToOne(targetEntity="AOFVH\UserBundle\Entity\User", inversedBy="comments", cascade={"persist", "merge"})
*/
private $commenter;
/**
* #var $commenter
*
* #ORM\ManyToOne(targetEntity="AOFVH\FlyBundle\Entity\Flight", inversedBy="comments", cascade={"persist", "merge"})
*/
private $flight;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set rating
*
* #param integer $rating
* #return Comment
*/
public function setRating($rating)
{
$this->rating = $rating;
return $this;
}
/**
* Get rating
*
* #return integer
*/
public function getRating()
{
return $this->rating;
}
/**
* Set text
*
* #param string $text
* #return Comment
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set commenter
*
* #param \AOFVH\UserBundle\Entity\User $commenter
* #return Comment
*/
public function setCommenter(\AOFVH\UserBundle\Entity\User $commenter = null)
{
$this->commenter = $commenter;
return $this;
}
/**
* Get commenter
*
* #return \AOFVH\UserBundle\Entity\User
*/
public function getCommenter()
{
return $this->commenter;
}
/**
* Set flight
*
* #param \AOFVH\FlyBundle\Entity\Flight $flight
* #return Comment
*/
public function setFlight(\AOFVH\FlyBundle\Entity\Flight $flight = null)
{
$this->flight = $flight;
return $this;
}
/**
* Get flight
*
* #return \AOFVH\FlyBundle\Entity\Flight
*/
public function getFlight()
{
return $this->flight;
}
Here are the postedOn getters and setters
/**
* Set postedon
*
* #param \DateTime $postedon
* #return Comment
*/
public function setPostedon($postedon)
{
$this->postedon = $postedon;
return $this;
}
/**
* Get postedon
*
* #return \DateTime
*/
public function getPostedon()
{
return $this->postedon;
}
}
I think it's your mapping in your entity, you don't use "datetime" doctrine format else your form type will try to generate a date with a string for example but for me "postedOn must always be defined on a new comment.You can update your entity constructor with : $this->setPostedOn(new \Datetime()); or you can use TimestampableTrait
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.