i have two tables news and news_category. for that i have created two mapping class using symfony command 'doctrine:mapping:convert'. the two file as bellow.
news.orm.yml.
News:
type: entity
table: news
fields:
newsId:
id: true
type: integer
unsigned: false
nullable: false
column: news_id
generator:
strategy: IDENTITY
newsTitle:
type: string
length: 255
fixed: false
nullable: false
column: news_title
newsDescription:
type: text
nullable: false
column: news_description
newsStatus:
type: string
length: 255
fixed: false
nullable: false
column: news_status
createdAt:
type: date
nullable: false
column: created_at
manyToOne:
category:
targetEntity: NewsCategory
cascade: { }
mappedBy: null
inversedBy: null
joinColumns:
category_id:
referencedColumnName: category_id
orphanRemoval: false
lifecycleCallbacks: { }
2). NewCategory.orm.yml
NewsCategory:
type: entity
table: news_category
fields:
categoryId:
id: true
type: integer
unsigned: false
nullable: false
column: category_id
generator:
strategy: IDENTITY
categoryTitle:
type: string
length: 255
fixed: false
nullable: false
column: category_title
categoryDescription:
type: text
nullable: false
column: category_description
lifecycleCallbacks: { }
after that i have used the another symfony command "doctrine:mapping:import" using this i have again generate two file in Entity folder News.php and NewsCategory.php
which is as bellow.
1) news.php
<?php
namespace Admin\NewsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* News
*
* #ORM\Table(name="news")
* #ORM\Entity
*/
class News
{
/**
* #var integer
*
* #ORM\Column(name="news_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $newsId;
/**
* #var string
*
* #ORM\Column(name="news_title", type="string", length=255, nullable=false)
*/
private $newsTitle;
/**
* #var string
*
* #ORM\Column(name="news_description", type="text", nullable=false)
*/
private $newsDescription;
/**
* #var string
*
* #ORM\Column(name="news_status", type="string", length=255, nullable=false)
*/
private $newsStatus;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="date", nullable=false)
*/
private $createdAt;
/**
* #var \NewsCategory
*
* #ORM\ManyToOne(targetEntity="NewsCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="category_id")
* })
*/
private $category;
}
And, 2) NewCategory.php
namespace Admin\NewsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* NewsCategory
*
* #ORM\Table(name="news_category")
* #ORM\Entity
*/
class NewsCategory
{
/**
* #var integer
*
* #ORM\Column(name="category_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $categoryId;
/**
* #var string
*
* #ORM\Column(name="category_title", type="string", length=255, nullable=false)
*/
private $categoryTitle;
/**
* #var string
*
* #ORM\Column(name="category_description", type="text", nullable=false)
*/
private $categoryDescription;
}
the problem is now when i am creating the Entities using the "doctrine:generate:entities"
it is giving me the following error.
D:\wamp\www\Symfony>php app/console doctrine:generate:entities AdminNewsBundle
Generating entities for bundle "AdminNewsBundle"
[Doctrine\Common\Persistence\Mapping\MappingException]
Invalid mapping file 'Admin.NewsBundle.Entity.News.orm.yml' for class 'Admi
n\NewsBundle\Entity\News'.
doctrine:generate:entities [--path="..."] [--no-backup] name
sorry for poor english please help me out come from this problem as i am new to symfony2
Try:
1) php app/console doctrine:mapping:convert yml ./src/Admin/NewsBundle/Resources/config/doctrine/metadata/orm --from-database --force --namespace="Admin\\NewsBundle\\Entity\\"
for Linux namespace="Admin\\NewsBundle\\Entity\\", for Win probably namespace="Admin\NewsBundle\Entity\\"
Watch that mapping is in right place, has correct names and correct syntax.
2) php app/console doctrine:mapping:import AdminNewsBundle annotation
3) php app/console doctrine:generate:entities AdminNewsBundle
Try replacing the first line of YML with the entity name with naspace
Admin\NewsBundle\Entity\News:
for exemple.
Related
config.yml
vich_uploader:
db_driver: orm
mappings:
media_image:
uri_prefix: '%uploads_dir%'
upload_destination: '%kernel.root_dir%/../web/uploads/images'
namer: Vich\UploaderBundle\Naming\OrignameNamer
Entity:
/**
* Media
* #Vich\Uploadable
* #ORM\Table(name="medias")
* #ORM\Entity(repositoryClass="AppBundle\Repository\MediaRepository")
*/
class Media
{
use TimestampableEntity;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #var string
*/
private $imageName;
/**
* #Vich\UploadableField(mapping="media_image", fileNameProperty="imageName", mimeType="mimeType", size="size")
* #var File
*/
private $imageFile;
/**
* #var string
*
* #ORM\Column(name="mime_type", type="string", length=20, nullable=true)
*/
private $mimeType;
/**
* #var string
*
* #ORM\Column(name="size", type="integer", nullable=true)
*/
private $size;
When I enable namer, I am getting this error:
Any ideas why?
The (custom-)namer should be registered as a service and referred to by its service name.
You can see the default (long) configuration together with a list of namer services provided by VichUploaderBundle in the example below:
vich_uploader:
# [..]
mappings:
product_image_file:
# [..]
namer:
# one of: vich_uploader.namer_{uniqid,origname,property,hash}
service: vich_uploader.namer_origname
For reference, here are all namer services as listed by the command bin/console debug:container:
vich_uploader.namer_base64 Vich\UploaderBundle\Naming\Base64Namer
vich_uploader.namer_directory_property Vich\UploaderBundle\Naming\PropertyDirectoryNamer
vich_uploader.namer_hash Vich\UploaderBundle\Naming\HashNamer
vich_uploader.namer_origname Vich\UploaderBundle\Naming\OrignameNamer
vich_uploader.namer_property Vich\UploaderBundle\Naming\PropertyNamer
vich_uploader.namer_uniqid Vich\UploaderBundle\Naming\niqidNamer
I have configured Symfony 3 to auto serialize my action. It works, but the relations aren't serialized:
0
id 1
name "Liste de course"
creation_date "2017-07-07T00:00:00+00:00"
last_update_date "2017-07-07T20:57:06+00:00"
user_entity
_todo_entity_entities
_parent_entity
1
id 2
name "domotique"
creation_date "2017-07-07T00:00:00+00:00"
last_update_date "2017-07-07T21:22:52+00:00"
user_entity
_todo_entity_entities
_parent_entity
If I explicitly use JMSSerializerBundle, it works (user_entity is an object):
0
id 1
name "Liste de course"
creation_date "2017-07-07T00:00:00+00:00"
last_update_date "2017-07-07T20:57:06+00:00"
user_entity Object
_todo_entity_entities
1
id 2
name "domotique"
creation_date "2017-07-07T00:00:00+00:00"
last_update_date "2017-07-07T21:22:52+00:00"
user_entity Object
_todo_entity_entities
I think FOSRestBundle uses the default seralizer, not JMSSerializerBundle:
/**
* #Rest\Get("/projects")
* #View(
* serializerGroups = {"all"}
* )
*/
public function getProjectsAction()
{
$projectEntity = $this->getDoctrine()->getRepository('todoListAdminBundle:Project');
$projects = $projectEntity->findAll();
/*
$data = $this->get('jms_serializer')->serialize($projects, 'json');
// this is work !
$response = new Response($data);
$response->headers->set('Content-Type', 'application/json');
return $response;
*/
return $projects;
}
The entity I serialize :
/**
* Project
*
* #ORM\Table(name="project")
* #ORM\Entity(repositoryClass="todoListAdminBundle\Repository\ProjectRepository")
*/
class Project
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Serializer\Groups({"all"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\Length(max=50)
* #Assert\Type(type="string")
* #Serializer\Groups({"all"})
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="creation_date", type="date")
* #Assert\DateTime()
* #Serializer\Groups({"all"})
*/
private $creationDate;
/**
* #var \DateTime
*
* #ORM\Column(name="last_update_date", type="datetime")
* #Assert\DateTime()
* #Serializer\Groups({"all"})
*/
private $lastUpdateDate;
/**
*
* #ORM\ManyToOne(targetEntity="PW\UserBundle\Entity\User", inversedBy="projectEntities" , cascade={"persist"}, inversedBy="projectEntities")
* #Assert\Type(type="integer")
* #Serializer\Groups({"all"})
*/
private $userEntity;
/**
* #ORM\OneToMany(targetEntity="todoListAdminBundle\Entity\TodoEntity", mappedBy="projectEntity", fetch="EAGER")
* #Serializer\Groups({"all"})
*/
private $TodoEntityEntities;
/**
* #var int
*
* #ORM\JoinColumn(nullable=true, referencedColumnName="id")
* #ORM\OneToOne(targetEntity="todoListAdminBundle\Entity\Project")
* #Assert\Type(type="integer")
* #Serializer\Groups({"all"})
*/
private $ParentEntity;
My configuration :
fos_rest:
param_fetcher_listener: true
body_listener: true
zone:
- { path: ^/api/* }
body_converter:
enabled: true
view:
formats: { json: true, xml: false, rss: false }
view_response_listener: true
serializer:
serialize_null: true
format_listener:
enabled: true
rules:
- { path: '^/api', priorities: ['json'], fallback_format: 'json' }
routing_loader:
default_format: json
sensio_framework_extra:
view: { annotations: true }
How can I use JMSSerializerBundle automatically ?
First of all, you need to configure JMSSerializer in your config.yml like:
jms_serializer:
metadata:
cache: file
debug: "%kernel.debug%"
file_cache:
dir: "%kernel.cache_dir%/serializer"
auto_detection: true
Then, create directory with serializer for the given entity YourBundleName/Resources/config/serializer/Entity.Project.yml with this code:
YourBundleName\Entity\Project:
exclusion_policy: ALL
properties:
id:
expose: true
name:
expose: true
"exclusion_policy: ALL" - exclude all the fields from the serialized result. And then you add needed fields with "expose: true". Just do not add "ParentEntity" there and you will not see it in the serialized data (also, I do not think, that mix of camel and pascal case is a good practice, but it's the question of taste).
I need to configure the payum bundle in order to let clients process paypal payments.
I just followed the getting started official recomendations, but need to configure something more, I guess (maybe I am missing to configure the storage for PaymentDetails somewhere).
my config files are as follows:
**app/config.yml**
doctrine:
orm:
auto_generate_proxy_classes: true
entity_managers:
default:
mappings:
WebsiteDeviceBundle: ~
WebsiteOnePageBundle: ~
payum:
is_bundle: false
type: xml
dir: %kernel.root_dir%/../vendor/payum/payum/src/Payum/Core/Bridge/Doctrine/Resources/mapping
prefix: Payum\Core\Model
payum:
security:
token_storage:
Website\Bundle\DeviceBundle\Entity\PaymentToken: { doctrine: orm }
storages:
Website\Bundle\DeviceBundle\Entity\PaymentDetails: { doctrine: orm }
contexts:
express_euro:
paypal_express_checkout_nvp:
username: ''
password: ''
signature: ''
sandbox: true
this is my controller action to start the payment process
public function prepareAction(){
$paymentName = 'express_euro';
$storage = $this->get('payum')->getStorage('Website\DeviceBundle\Entity\PaymentDetails');
$order = $storage->createModel();
$order->setNumber(uniqid());
$order->setCurrencyCode('EUR');
$order->setTotalAmount($this->view['user']->money);
$order->setDescrizione('annual account subscription');
$order->setUser($this->view['user']->getId());
$order->setCreatedAt(new \DateTime());
$order->setClientEmail($this->view['user']->getEmail());
$storage->updateModel($order);
$captureToken = $this->get('payum.security.token_storage')->createCaptureToken(
$paymentName,
$order,
'done' // the route to redirect after capture;
);
return $this->redirect($captureToken->getTargetUrl());
}
and this is PaymentDetails class
<?php
namespace Website\Bundle\DeviceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Payum\Core\Model\ArrayObject;
/**
* PaymentDetails
*
* #ORM\Table(name="PaymentDetails", indexes={#ORM\Index(name="user", columns={"user"})})
* #ORM\Entity(repositoryClass="Website\Bundle\DeviceBundle\Entity\PaymentsDetailsRepository")
*/
class PaymentDetails extends ArrayObject
{
/**
* #var string
*
* #ORM\Column(name="currency_code", type="string", length=255, nullable=false)
*/
private $currencyCode;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
*/
private $createdAt;
/**
* #var integer
*
* #ORM\Column(name="number", type="integer", nullable=false)
*/
private $number;
/**
* #var integer
*
* #ORM\Column(name="total_amount", type="integer", nullable=false)
*/
private $totalAmount;
/**
* #var string
*
* #ORM\Column(name="client_email", type="text", nullable=false)
*/
private $clientEmail;
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Website\Bundle\DeviceBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Website\Bundle\DeviceBundle\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user", referencedColumnName="id")
* })
*/
private $user;
and the error it comes when I GET the doneAction() url, is this
A storage for model Website\DeviceBundle\Entity\PaymentDetails was not registered. There are storages for next models: Website\Bundle\DeviceBundle\Entity\PaymentDetails.
any helps or suggestions?
thank you in advance
just changed this line
$storage = $this->get('payum')->getStorage('Website\DeviceBundle\Entity\PaymentDetails');
into
$storage = $this->get('payum')->getStorage('Website\Bundle\DeviceBundle\Entity\PaymentDetails');
and now it works.
I am trying to create a symfony2 application. The main idea behind the project is that there is an event which many guests are invited to and they are categorized. I have created a relational model for all the entities.
There are 4 tables:
Guests - who is invited
Category - what category/categories he belongs to ?
Event - the event which they are invited to
Guest_Event (attendance)
I have concluded to the following schemas:
xxxxBundle\Entity\Guest:
type: entity
table: guest
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 100
nullable: false
surname:
type: string
length: 100
nullable: false
email:
type: string
length: 255
nullable: true
address:
type: string
length: 255
nullable: true
phone:
type: string
length: 10
description:
type: text
created_at:
type: datetime
updated_at:
type: datetime
nullable: true
token:
type: string
length: 255
unique: true
is_activated:
type: boolean
nullable: true
manyToOne:
category:
targetEntity: Category
inversedBy: guest
joinColumn:
name: category_id
referencedColumnName: id
lifecycleCallbacks:
prePersist: [ setCreatedAtValue ]
preUpdate: [ setUpdatedAtValue ]
Category
xxxxBundle\Entity\Category:
type: entity
table: category
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 255
unique: true
oneToMany:
guests:
targetEntity: Guest
mappedBy: category
attend:
targetEntity: Attendance
mappedBy: category
Event
xxxxxBundle\Entity\Event:
type: entity
table: event
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 100
nullable: false
location:
type: string
length: 255
nullable: true
scheduled_at:
type: datetime
manyToMany:
category:
targetEntity: guest
inversedBy: event
joinColumn:
name: event_id
referencedColumnName: id
A guest might belong to multiple categories (manyToOne)
A category will have many guests (manyToOne)
A guest might attend many events (manyToOne)
An event might have many attendants (manyToMany?)
the attendance table (guest_event) should be a join table ?
I am a little bit confused about ORM and doctrine coding. Creating the tables via SQL code or phpmyadmin seems much easier to me but I want to go the hard way ! The documentation seems confusing because each tutorial suggests different things and the doctrine ORM section in the symfony2 book doesn't have a complete example but pieces of code..
How can I correct my tables to include all the specifications ?
My two cents:
A guest might belong to multiple categories
So many guests can belong to many categories, so it's many to many guest side. Assuming the owning side is Guest:
xxxxBundle\Entity\Guest:
manyToMany:
categories:
targetEntity: Category
inversedBy: guests
joinTable:
name: guests_categories
A category will have many guests (manyToOne)
If category will have many guests, why is's many to one? Many categories can be assigned to many guest:
xxxxBundle\Entity\Category:
manyToMany:
guests:
targetEntity: Guest
mappedBy: categories
If i understand you correctly, a categoy may exist even without a guest, and vice-versa a guest may exist even without a category.
And for guest/events relation, i'll go again for many to many / many to many. Take a look at here and ask yourself: one/many type of my entity can have one/many type of another entity?
I would strongly suggest you work your way through the official Symfony 2 documentation:
http://symfony.com/doc/master/book/doctrine.html
It takes you step by step through the process of initializing the database, making an entity, mapping it to the database and then using the entity.
You are trying to understand multiple concepts by reading assorted documentation. The fact that you seem to have yaml files in your entity directory indicates a basic lack of understanding.
Go through the tutorial first then add in your real entities. It's pretty straight forward once you get a few things working.
I changed my mind and used annotations as yaml seems confusing to me.
So far :
For the Guest entity
<?php
// xxxxBundle/Entity/Guest.php
namespace xxxxBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="guest")
*/
class Guest
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ManyToMany(targetEntity="Category", inversedBy="guests")
* #JoinTable(name="guests_categories")
*/
protected $categories;
/**
* #ManyToMany(targetEntity="Event", inversedBy="events")
* #JoinTable(name="guests_events")
*/
protected $events;
/**
* #ORM\Column(type="string", length=30)
*/
protected $name;
/**
* #ORM\Column(type="string", length=30)
*/
protected $surname;
/**
* #ORM\Column(type="string", length=30)
*/
protected $email;
/**
* #ORM\Column(type="string", length=100)
*/
protected $address;
/**
* #ORM\Column(type="string", length=10)
*/
protected $phone;
/**
* #ORM\Column(type="string", length=10)
*/
protected $mobile;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\Column(type="datetime")
*/
protected $created_at;
/**
* #ORM\Column(type="datetime")
*/
protected $updated_at;
/**
* #ORM\Column(type="string")
*/
protected $token;
/**
* #ORM\Column(type="boolean")
*/
protected $is_activated;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
$metadata->addPropertyConstraint('surname', new NotBlank());
$metadata->addPropertyConstraint('email', new Email(array(
'message' => 'I do not like invalid emails. Give me a real one!')));
$metadata->addPropertyConstraint('phone', new MaxLength(10));
$metadata->addPropertyConstraint('mobile', new MaxLength(10));
}
}
For the Category entity
<?php
// xxxxBundle/Entity/Category.php
namespace xxxxBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="category")
*/
class Category
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ManyToMany(targetEntity="Guest", mappedBy="categories")
*/
protected $guests;
/**
* #ORM\Column(type="string", length=30)
*/
protected $name;
/**
* #ORM\Column(type="text")
*/
protected $description;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
}
}
For the Event entity
<?php
// xxxxBundle/Entity/Event.php
namespace xxxxBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="event")
*/
class Event
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ManyToMany(targetEntity="Guest", mappedBy="categories")
*/
protected $guests;
/**
* #ORM\Column(type="string", length=30)
*/
protected $name;
/**
* #ORM\Column(type="string", length=100)
*/
protected $location;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\Column(type="datetime")
*/
protected $scheduled_at;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
$metadata->addPropertyConstraint('location', new NotBlank());
}
}
I feel confused about the Attendance entity. The Attendance entity will have the following variables:
Guest_id
Event_id
Will_attend (yes/no/maybe)
Comment
Replied_at
Updated_at
I do not know which will be the primary key (or the primary keys?). The db table does not need to have a separate Id (or not?).
<?php
// xxxxBundle/Entity/Attendance.php
namespace xxxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="attendance")
*/
class Attendance
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ManyToMany(targetEntity="Guest", mappedBy="categories")
*/
protected $guests;
/**
* #ManyToMany(targetEntity="Event", mappedBy="events")
*/
protected $events;
/**
* #ORM\Column(type="string", length=3)
*/
protected $will_attend;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\Column(type="datetime")
*/
protected $replied_at;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
}
The attendance entity requires a person to declare while he/she will attend an event or not. That means that it's a oneToOne relation because for every event must be ONE event - ONE person - ONE attendance reply.
The solution is to change the following code in the attendance entity :
/**
* #ORM\OneToOne(targetEntity="Guest")
*/
protected $guests;
/**
* #ORM\OneToOne(targetEntity="Event")
*/
protected $events;
Then run php app/console doctrine:generate:entities , php app/console doctrine:schema:update --force and the crud command If you generate them automatically. Now everything works fine.
I'm trying to apply Doctrine to an existing database that has a OneToMany relationship between two tables: Commerce and Area.
I generated the yml schema from the database resulting in the following:
Area:
type: entity
table: area
fields:
id:
id: true
type: integer
unsigned: false
nullable: false
generator:
strategy: IDENTITY
name:
type: string
length: 255
fixed: false
nullable: true
lifecycleCallbacks: { }
Commerce:
type: entity
table: commerce
fields:
id:
id: true
type: integer
unsigned: false
nullable: false
generator:
strategy: IDENTITY
name:
type: string
length: 255
fixed: false
nullable: true
manyToOne:
area:
targetEntity: Area
cascade: { }
mappedBy: null
inversedBy: null
joinColumns:
area_id:
referencedColumnName: id
orphanRemoval: false
lifecycleCallbacks: { }
From that schema I generated the Entities:
use Doctrine\ORM\Mapping as ORM;
/**
* Model\EntitiesBundle\Entity\Area
*
* #ORM\Table(name="area")
* #ORM\Entity
*/
class Area
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #return string
*/
public function getName()
{
return $this->name;
}
}
use Doctrine\ORM\Mapping as ORM;
/**
* Model\EntitiesBundle\Entity\Commerce
*
* #ORM\Table(name="commerce")
* #ORM\Entity
*/
class Commerce
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #var Area
*
* #ORM\ManyToOne(targetEntity="Area")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="area_id", referencedColumnName="id")
* })
*/
private $area;
/**
* #return \Model\EntitiesBundle\Entity\Area
*/
public function getArea()
{
return $this->area;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
}
My problem comes when I try:
$commerce = $em->getRepository('ModelEntitiesBundle:Commerces')
->find($id);
echo $commerce->getArea()->getName();
The Area entity has empty attributes.
Any ideas? Thank you!
I solved the problem. It was somewhere else, I have two Entity Managers and the one I needed was not the default.