Symfony2 - Serialize object with relations (ManyToMany, OneToMany ...) - php

Can someone tell me if it's possible to serialize an entity that have relations ?
json_encode already works but my object looks like this :
{
"id": 1,
"lot": 32,
"num": "533987",
"date_modification": {
"date": "2015-02-17 14:24:52",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"customer": {
"id": 1,
"lastname": "DUFRESNE",
"firstname": "CHRISTOPHE",
}
}
But i would like to serialize data withotu sub objects. in fact like this :
{
"id": 1,
"lot": 32,
"num": "533987",
"date_modification": "2015-02-17",
"customer": "DUFRESNE CHRISTOPHE",
}
}
So i checked the doc : http://symfony.com/doc/current/components/serializer.html
But i can't see if it's possible to works with relations like ManyToMany, etc and how to do it ?
Here is my Entity :
/**
* Subscription (BS)
*
* #ORM\Table(name="subscription")
* #ORM\Entity(repositoryClass="Jcd\LiteyearBundle\Entity\SubscriptionRepository")
* #ORM\HasLifecycleCallbacks
*/
class Subscription {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="lot", type="smallint")
*/
private $lot;
/**
* #var string
* #ORM\Column(name="num", type="string", length=9)
*/
private $num;
/**
* #var \DateTime
* #ORM\Column(name="date_creation", type="datetime", nullable=true)
*/
private $date_creation;
/**
* #var \DateTime
* #ORM\Column(name="date_modification", type="datetime", nullable=true)
*/
private $date_modification;
/**
* #var \DateTime
* #ORM\Column(name="date_completeness", type="datetime", nullable=true)
*/
private $date_completeness;
/**
* #var \DateTime
* #ORM\Column(name="date_reception", type="datetime", nullable=true)
*/
private $date_reception;
/**
* #var \DateTime
* #ORM\Column(name="date_signature", type="datetime", nullable=true)
*/
private $date_signature;
/**
* #var \DateTime
* #ORM\Column(name="date_entry", type="datetime", nullable=true)
*/
private $date_entry;
/**
* #var \Integer
* #ORM\Column(name="statement", type="integer", nullable=true)
*/
private $statement; // Releve du compteur
/**
* #var \Integer
* #ORM\Column(name="statement_kind", type="integer", nullable=true)
*/
private $statement_kind; // Personne qui a relevé le compteur
/**
* #var \Integer
* #ORM\Column(name="car", type="integer", nullable=true)
*/
private $car; // Consommation annuelle de reference
/**
* #var boolean
* #ORM\Column(name="pro", type="boolean", options={"default" = false}, nullable=true)
*/
private $pro;
/**
* #ORM\ManyToOne(targetEntity="Jcd\LiteyearBundle\Entity\User", cascade={"persist"}, inversedBy="adv_subscriptions")
* #ORM\JoinColumn(name="adv_id", referencedColumnName="id", nullable=true)
*/
private $adv;
/**
* #ORM\ManyToOne(targetEntity="Jcd\LiteyearBundle\Entity\User", cascade={"persist"}, inversedBy="vendor_subscriptions")
* #ORM\JoinColumn(name="vendor_id", referencedColumnName="id", nullable=true)
*/
private $vendor;
/**
* #var \Integer
* #ORM\Column(name="provider", type="integer")
*/
private $provider;
/**
* #var \Integer
* #ORM\Column(name="state", type="integer")
*/
private $state;
/**
* #var \Integer
* #ORM\Column(name="payment", type="integer")
*/
private $payment;
/**
* #var \Integer
* #ORM\Column(name="billing", type="integer")
*/
private $billing;
/**
* #var string
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #var float
* #ORM\Column(name="wage", type="float", nullable=true)
*/
private $wage; // Anciennement Rem
/**
* #var float
* #ORM\Column(name="com", type="float", nullable=true)
*/
private $com; // Anciennement Commission
/**
* #var string
* #ORM\Column(name="offer", type="text", nullable=true)
*/
private $offer; // Anciennement Prix fixe
/**
* #var \Integer
* #ORM\Column(name="mail_kind", type="integer", nullable=true)
*/
private $mail_kind; //Anciennement Mail
/**
* #ORM\OneToMany(targetEntity="SubscriptionTrack", cascade={"persist", "remove"}, mappedBy="subscription")
*/
private $tracks;
/**
* #ORM\ManyToMany(targetEntity="SubscriptionSalary", cascade={"persist"}, mappedBy="subscriptions")
**/
private $salaries;
/**
* #ORM\OneToOne(targetEntity="Jcd\LiteyearBundle\Entity\Customer")
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id")
**/
private $customer;
Thank you for you answer !

The easiest way to achieve what you want is to use JMSSerializerBundle that has many features that you might want to use.
Give it a try: http://jmsyst.com/bundles/JMSSerializerBundle

Related

doctrine : generate entities from the database

I'm using doctrine to generate the entities from database in command line
doctrine orm:convert-mapping --force --from-database annotation ./Api/Entity
The php class is created correctly but when i try to use the repository to load the entity from the database
$decompte=$entityManager->getRepository(Decompte::class)->find(31);
I'm getting this exception
Class "entity\Decompte" is not a valid entity or mapped super class.
and please find above the entire code of the class entity\Decompte
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* Decompte
*
* #ORM\Table(name="decompte", indexes={#ORM\Index(name="N°D", columns={"ID"})})
* #ORM\Entity
*/
class Decompte
{
/**
* #var int
*
* #ORM\Column(name="ID", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int|null
*
* #ORM\Column(name="NPRIXD", type="integer", nullable=true)
*/
private $nprixd;
/**
* #var string|null
*
* #ORM\Column(name="DESIGNATIOND", type="string", length=43, nullable=true)
*/
private $designationd;
/**
* #var string|null
*
* #ORM\Column(name="UNITED", type="string", length=2, nullable=true)
*/
private $united;
/**
* #var int|null
*
* #ORM\Column(name="QTED", type="integer", nullable=true)
*/
private $qted;
/**
* #var int|null
*
* #ORM\Column(name="PRIXHTD", type="integer", nullable=true)
*/
private $prixhtd;
/**
* #var string|null
*
* #ORM\Column(name="DECOMPTED", type="string", length=2, nullable=true)
*/
private $decompted;
/**
* #var int|null
*
* #ORM\Column(name="TOTALD", type="integer", nullable=true)
*/
private $totald;
/**
* #var string|null
*
* #ORM\Column(name="QMARCHE", type="string", length=11, nullable=true)
*/
private $qmarche;
/**
* #var string|null
*
* #ORM\Column(name="QDECOMPTE", type="string", length=5, nullable=true)
*/
private $qdecompte;
/**
* #var int|null
*
* #ORM\Column(name="SMARCHE", type="integer", nullable=true)
*/
private $smarche;
/**
* #var string|null
*
* #ORM\Column(name="SDECOMPTE", type="string", length=6, nullable=true)
*/
private $sdecompte;
/**
* #var int|null
*
* #ORM\Column(name="NDMR", type="integer", nullable=true)
*/
private $ndmr;
/**
* #var string|null
*
* #ORM\Column(name="RESTE", type="string", length=11, nullable=true)
*/
private $reste;
/**
* #var string|null
*
* #ORM\Column(name="RESTEF", type="string", length=11, nullable=true)
*/
private $restef;
}
when trying to debug this issue, i found out that the Annotation Driver reader's cache is empty
i've added somme "echo" in the AnnotationDriver::loadMetaDataForClass
echo 'allClassName'.$this->getAllClassNames();
echo 'allPaths'.$this->getPaths();
returns an empty array
$classAnnotations = $this->reader->getClassAnnotations($class);
is also empty
thank you very much for you help

Symfony 3 and EasyAdminBundle: Form's text field don't work properly

I'm going to working in a Admin Backend to a WebPage with Symfony 2.2.8 and Javier Eguiluz's EasyAdminBundle 1.16.12 (last version). I installed the bundle following the instructions in GitHub page, and I have also created a couple of test entities (Users and Engagementes).
Well, my trouble is that the text type in the edit template not working, they are empty and without label, otherwise the entity can be edited correctly.
User:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="User")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User
{
/**
* #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=50, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="surname", type="string", length=255, nullable=true)
*/
private $surname;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=50, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="role", type="string", length=50)
*/
private $role;
// getter and setter [...]
Engagement:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Engagement
*
* #ORM\Table(name="Engagement")
* #ORM\Entity(repositoryClass="AppBundle\Repository\EngagementRepository")
*/
class Engagement
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=20, unique=true)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="owner", type="string", length=255)
*/
private $owner;
/**
* #var int
*
* #ORM\Column(name="phone", type="integer", nullable=true)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="incident", type="string", length=255)
*/
private $incident;
/**
* #var string
*
* #ORM\Column(name="brand", type="string", length=50, nullable=true)
*/
private $brand;
/**
* #var string
*
* #ORM\Column(name="model", type="string", length=255, nullable=true)
*/
private $model;
/**
* #var string
*
* #ORM\Column(name="repairer", type="string", length=255, nullable=true)
*/
private $repairer;
/**
* #var float
*
* #ORM\Column(name="cost", type="float", nullable=true)
*/
private $cost;
/**
* #var float
*
* #ORM\Column(name="advance", type="float", nullable=true)
*/
private $advance;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="datetime")
*/
private $startDate;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=50)
*/
private $status;
/**
* #var string
*
* #ORM\Column(name="comment", type="string", length=255, nullable=true)
*/
private $comment;
// setters and getters [...]
Config.yml:
# [...]
easy_admin:
entities:
- AppBundle\Entity\User
- AppBundle\Entity\Engagement
And I get it with EasyAdminBundle:
P.S.: I'm sorry if I made mistakes, English is not my native language.

An index with name 'primary' was already defined on table 'sites'

I am using Doctrine 2 with ZF2.
I have a sites entity with the following primary key field.
/**
* #var string
* #ORM\Column(name="site_id", type="string", length=10, nullable=false)
* #ORM\Id
*/
private $siteId;
And the following index's
* #ORM\Table(name="sites", indexes={
* #ORM\Index(name="PRIMARY", columns={"site_id"}),
* #ORM\Index(name="country_id", columns={"country_id"}),
* #ORM\Index(name="timezone_id", columns={"timezone_id"}),
* #ORM\Index(name="vat_rate_id", columns={"vat_rate_id"}),
* #ORM\Index(name="site_mode_id", columns={"site_mode_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* })
When I run php ./vendor/doctrine/doctrine-module/bin/doctrine-module orm:validate-schema from the command line I get the following error message.
[Doctrine\DBAL\Schema\SchemaException]
An index with name 'primary' was already defined on table 'sites'.
However it also reports The mapping files are correct.
Does anyone know why this error is being generated?
Many thanks in advance.
EDIT
Full entity as requested
/**
* Sites Entity
*
* #author Garry Childs
*
* #ORM\Table(name="sites", indexes={
* #ORM\Index(name="country_id", columns={"country_id"}),
* #ORM\Index(name="timezone_id", columns={"timezone_id"}),
* #ORM\Index(name="vat_rate_id", columns={"vat_rate_id"}),
* #ORM\Index(name="site_mode_id", columns={"site_mode_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* })
* #ORM\Entity(repositoryClass="Application\Entity\Repository\SitesRepository")
* #ORM\HasLifecycleCallbacks
*/
class Sites extends AbstractEntity
{
/**
* #var string
* #ORM\Column(name="site_id", type="string", length=10, nullable=false)
* #ORM\Id
*/
private $siteId;
/**
* #var string
*
* #ORM\Column(name="domain_name", type="string", length=255, nullable=false)
*/
private $domainName;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=30, nullable=false)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="email_address", type="string", length=254, nullable=false)
*/
private $emailAddress;
/**
* #var string
*
* #ORM\Column(name="layout", type="string", length=30, nullable=true)
*/
private $layout;
/**
* #var string
*
* #ORM\Column(name="homepage", type="string", length=30, nullable=true)
*/
private $homepage;
/**
* #var string
*
* #ORM\Column(name="bookmark_icon", type="string", length=20, nullable=false)
*/
private $bookmarkIcon = 'bookmark.png';
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=200, nullable=false)
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="town", type="string", length=30, nullable=false)
*/
private $town;
/**
* #var string
*
* #ORM\Column(name="county", type="string", length=30, nullable=false)
*/
private $county;
/**
* #var \Application\Entity\Countries
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Countries")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="country_id")
* })
*/
private $country;
/**
* #var string
*
* #ORM\Column(name="post_code", type="string", length=7, nullable=false)
*/
private $postCode;
/**
* #var \Application\Entity\Timezones
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Timezones")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="timezone_id", referencedColumnName="timezone_id")
* })
*/
private $timezone;
/**
* #var string
*
* #ORM\Column(name="locale", type="string", length=5, nullable=false)
*/
private $locale;
/**
* #var string
*
* #ORM\Column(name="currency_code", type="string", length=3, nullable=false)
*/
private $currencyCode;
/**
* #var string
*
* #ORM\Column(name="vat_number", type="string", length=10, nullable=true)
*/
private $vatNumber;
/**
* #var \Application\Entity\VatRates
*
* #ORM\ManyToOne(targetEntity="Application\Entity\VatRates", inversedBy="sites")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="vat_rate_id", referencedColumnName="vat_rate_id")
* })
*/
private $vatRate;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modified", type="datetime")
*/
private $dateModified;
/**
* #var \Application\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="created_by_user_id", referencedColumnName="user_id")
* })
*/
private $createdBy;
/**
* #var Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\Categories", mappedBy="site")
*/
private $categories;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\SiteCountries", cascade="persist", mappedBy="site")
*/
private $siteCountries;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\SiteShippingMethods", cascade="persist", mappedBy="site")
*/
private $shippingMethods;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\SitePaymentMethods", cascade="persist", mappedBy="site")
*/
private $sitePaymentMethods;
/**
* #var \Application\Entity\SiteModes
*
* #ORM\ManyToOne(targetEntity="Application\Entity\SiteModes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_mode_id", referencedColumnName="site_mode_id")
* })
*/
private $siteMode;
/**
*
* #var integer
* #ORM\Column(name="payment_days", type="integer", nullable=false)
*/
private $paymentDays;
/**
*
* #var integer
* #ORM\Column(name="products_per_page", type="integer", nullable=false)
*/
private $productsPerPage;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\Invoices", mappedBy="site")
* })
*/
private $invoices;
public function __construct()
{
$this->categories = new ArrayCollection();
$this->siteCountries = new ArrayCollection();
$this->shippingMethods = new ArrayCollection();
$this->vatRate = NULL;
$this->sitePaymentMethods = new ArrayCollection();
$this->invoices = new ArrayCollection();
$this->productsPerPage = 15;
}
.... Getters & Setters
/**
* #ORM\PrePersist
* #return \Application\Entity\Users
*/
public function prePersist()
{
$this->dateCreated = $this->getCurrentDateTime();
$this->dateModified = $this->getCurrentDateTime();
$this->currencyCode = $this->strToUpper($this->currencyCode);
$this->createdBy = $this->getAuthUser();
return $this;
}
/**
* #ORM\PreUpdate
* #return \Application\Entity\Users
*/
public function preUpdate()
{
$this->dateModified = $this->getCurrentDateTime();
$this->currencyCode = $this->strToUpper($this->currencyCode);
return $this;
}
You already marked the site_id column as your primary column when you added #ORM\Id annotation to the $siteId property. It is not necessary to add the following line:
#ORM\Index(name="PRIMARY", columns={"site_id"}),
Remove that line and you will see that the site_id column will be indexed properly as PRIMARY index automatically in your database.
Read more on this in chapter 4.5. Identifiers / Primary Keys in the doctrine documentation

Doctrine - How to create inverse relation?

In symfony I created two entities from a database already created. I used the following commands from the console of symfony:
php app/console doctrine:mapping:import --force IDFrontendBundle xml
php app/console doctrine:mapping:convert annotation ./src
php app/console doctrine:generate:entities IDFrontendBundle
Two of the entities that generate me and where I have the problem are as follows
use Doctrine\ORM\Mapping as ORM;
/**
* ProviderRate
*
* #ORM\Table(name="provider_rate", indexes={#ORM\Index(name="fk_proveedor_has_producto_compra_producto_compra1_idx", columns={"product_id"}), #ORM\Index(name="fk_id_tarifa_proveedor_id_moneda1_idx", columns={"currency_id"}), #ORM\Index(name="IDX_3A645C45A53A8AA", columns={"provider_id"})})
* #ORM\Entity(repositoryClass="IDavid\FrontendBundle\Entity\ProviderRateRepository")
*/
class ProviderRate
{
/**
* #var string
*
* #ORM\Column(name="reference", type="string", length=45, nullable=false)
*/
private $reference;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=true)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="unit_price", type="decimal", precision=25, scale=3, nullable=false)
*/
private $unitPrice;
/**
* #var string
*
* #ORM\Column(name="discount", type="decimal", precision=25, scale=3, nullable=false)
*/
private $discount;
/**
* #var \IDavid\FrontendBundle\Entity\Providers
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="IDavid\FrontendBundle\Entity\Providers")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="provider_id", referencedColumnName="id")
* })
*/
private $provider;
/**
* #var \IDavid\FrontendBundle\Entity\Products
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="IDavid\FrontendBundle\Entity\Products")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* })
*/
private $product;
/**
* #var \IDavid\FrontendBundle\Entity\Currencies
*
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\Currencies")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="currency_id", referencedColumnName="id")
* })
*/
private $currency;
and
use Doctrine\ORM\Mapping as ORM;
/**
* Products
*
* #ORM\Table(name="products", uniqueConstraints={#ORM\UniqueConstraint(name="id_producto_UNIQUE", columns={"id"})}, indexes={#ORM\Index(name="fk_id_productos_id_categorias1_idx", columns={"category_id"}), #ORM\Index(name="fk_id_productos_id_producto_tipo1_idx", columns={"type"}), #ORM\Index(name="fk_id_productos_id_moneda1_idx", columns={"currency_id"})})
* #ORM\Entity(repositoryClass="IDavid\FrontendBundle\Entity\ProductsRepository")
*/
class Products
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=45, nullable=false)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="description_long", type="text", nullable=false)
*/
private $descriptionLong;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=false)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="weight", type="decimal", precision=11, scale=3, nullable=false)
*/
private $weight;
/**
* #var string
*
* #ORM\Column(name="web", type="string", length=100, nullable=false)
*/
private $web;
/**
* #var boolean
*
* #ORM\Column(name="isActive", type="boolean", nullable=false)
*/
private $isactive;
/**
* #var \DateTime
*
* #ORM\Column(name="createdtime", type="datetime", nullable=false)
*/
private $createdtime;
/**
* #var \DateTime
*
* #ORM\Column(name="modifiedtime", type="datetime", nullable=false)
*/
private $modifiedtime;
/**
* #var \DateTime
*
* #ORM\Column(name="deletedtime", type="datetime", nullable=true)
*/
private $deletedtime;
/**
* #var boolean
*
* #ORM\Column(name="isDeleted", type="boolean", nullable=false)
*/
private $isdeleted;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \IDavid\FrontendBundle\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\Categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \IDavid\FrontendBundle\Entity\ProductTypes
*
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\ProductTypes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="type", referencedColumnName="id")
* })
*/
private $type;
/**
* #var \IDavid\FrontendBundle\Entity\Currencies
*
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\Currencies")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="currency_id", referencedColumnName="id")
* })
*/
private $currency;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="IDavid\FrontendBundle\Entity\Sets", inversedBy="product")
* #ORM\JoinTable(name="products_sets",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="set_id", referencedColumnName="id")
* }
* )
*/
private $set;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="IDavid\FrontendBundle\Entity\Products", mappedBy="productParentid")
*/
private $product;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="IDavid\FrontendBundle\Entity\Documents", inversedBy="product")
* #ORM\JoinTable(name="product_attachments",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
* }
* )
*/
private $document;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="IDavid\FrontendBundle\Entity\Images", inversedBy="product")
* #ORM\JoinTable(name="products_images",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="image_id", referencedColumnName="id")
* }
* )
*/
private $image;
/**
* Constructor
*/
public function __construct()
{
$this->set = new \Doctrine\Common\Collections\ArrayCollection();
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
$this->document = new \Doctrine\Common\Collections\ArrayCollection();
$this->image = new \Doctrine\Common\Collections\ArrayCollection();
$this->providerRate = new \Doctrine\Common\Collections\ArrayCollection();
}
I tried creating a new variable to join the two tables in reverse order into the product class
/**
* #ORM\OneToMany(targetEntity="IDavid\FrontendBundle\Entity\ProviderRate", inversedBy="product")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id", referencedColumnName="product_id")
* })
*/
private $providerRate;
But when I make a DQL query, symfony tells me that there is no association.
Is there any way to do this?
$dql = "SELECT p, pr FROM IDFrontendBundle:Products p
JOIN p.providerRate pr";
$query = $this->getEntityManager()->createQuery($dql);
You relationship cardinality is different on each side.
ProviderRate -> Product (OneToOne)
Product -> ProviderRate (OneToMany)
As such, it won't work. OneToOne should be on both sides or, OneToMany should be paired with ManyToOne.
I assume the following:
One Product can has multiple ProviderRates. It that correct?
If so, you need:
ProviderRate class
/**
* #var \IDavid\FrontendBundle\Entity\Products
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\Products", mappedBy="providerRate")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* })
*/
private $product;
Products class
/**
* #ORM\OneToMany(targetEntity="IDavid\FrontendBundle\Entity\ProviderRate", inversedBy="product")
*/
private $providerRate;
As you can see, once you declase #JoinColums on either of relationshp's sides, there is no need to specify one on other side. Also, inversedBy should be matched by mappedBy.
Does this help?
EDIT
Change mappedBy and inversedBy attribute order.
ProviderRate class
/**
* #var \IDavid\FrontendBundle\Entity\Products
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\ManyToOne(targetEntity="IDavid\FrontendBundle\Entity\Products", inversedBy="providerRate")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* })
*/
private $product;
Products class
/**
* #ORM\OneToMany(targetEntity="IDavid\FrontendBundle\Entity\ProviderRate", mappedBy="product")
*/
private $providerRate;

Doctrine - ManyToOne with table between

I want to create model which will have table users with reference to table CustomFieldValue nad table CustomField with reference to CustomFieldValue too. CustomFieldValue will have only id, value and two columns, one from users and second from CustomField. I want to have functionality like a dynamic adding a new fields in registration form. Is this good idea? If yes, please help me with this model, because it doesn't work:
User:
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users",cascade={"persist"})
*
*/
private $roles;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=60)
*/
private $sex;
/**
* #ORM\ManyToMany(targetEntity="Region", inversedBy="users")
* #ORM\JoinColumn(name="region", referencedColumnName="id")
*/
private $region;
/**
* #ORM\ManyToMany(targetEntity="Type", inversedBy="users")
* #ORM\JoinColumn(name="type", referencedColumnName="id")
*/
private $type;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToOne(targetEntity="CustomFieldValue",inversedBy="id")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $customValues;
CustomFieldValue:
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="value", type="string", length=255)
*/
private $value;
/**
*ORM\OneToMany(targetEntity="User", mapped-by="id")
*#ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
*#ORM\OneToMany(targetEntity="CustomField", mapped-by="id" )
*#ORM\JoinColumn(name="field_id", referencedColumnName="id")
*/
private $field;
CustomField:
/**
* #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\Column(name="type", type="string", length=255)
*/
private $type;
/**
* #var boolean
*
* #ORM\Column(name="required", type="boolean")
*/
private $required;
/**
* #ORM\ManyToOne(targetEntity="CustomFieldValue", inversedBy="id")
* #ORM\JoinColumn(name="customfield_id", referencedColumnName="id")
*/
private $customValues;
Your mapping is a little off:
User Entity Should Be:
/**
* #ORM\ManyToOne(targetEntity="CustomFieldValue", inversedBy="user")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $customValues;
CustomFieldValue Should Be:
/**
*ORM\OneToMany(targetEntity="User", mappedBy="customValues")
*/
private $user;
/**
*#ORM\OneToMany(targetEntity="CustomField", mappedBy="customValues" )
*/
private $field;
CustomField should be:
/**
* #ORM\ManyToOne(targetEntity="CustomFieldValue", inversedBy="field")
* #ORM\JoinColumn(name="customfield_id", referencedColumnName="id")
*/
private $customValues;
You dont need the join columns when you are calling the mappedBy this already tells doctrine to look for the join column declaration on that field. For the mappedBy and inversedBy fields these are the fields that link the 2 together NOT the actual join column name.

Categories