Zend Framework 2 : Generate Doctrine Entities from Existing Database using DoctrineModule and DoctrineORMModule
If we are working with Doctrine , we usually create entities first, and generate the database tables. How if the situation is the database tables and data is already ready, and we have to create an application based on doctrine and Zend Framework 2? We need generate entities! Don’t create them manually!
For example, i have two tables : album and track (i’m using PostgreSQL ) like the following :
-- Table: album CREATE TABLE album ( id bigserial NOT NULL, artist character varying(255), title character varying(255), CONSTRAINT pk_album PRIMARY KEY (id ) ) WITH ( OIDS=FALSE ); ALTER TABLE album OWNER TO developer; -- Table: track CREATE TABLE track ( track_id bigserial NOT NULL, track_title character varying(255), album_id bigint, CONSTRAINT track_pkey PRIMARY KEY (track_id ), CONSTRAINT fk_track_album FOREIGN KEY (album_id) REFERENCES album (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE ) WITH ( OIDS=FALSE ); ALTER TABLE track OWNER TO developer;
Ok, let’s create an application based on ZF2 step by step :
1. install ZF2 SkeletonApplication
git clone git://github.com/zendframework/ZendSkeletonApplication.git zftutordoctrine
2. add “doctrine/doctrine-orm-module” to your zftutordoctrine/composer.json
{ "name": "zendframework/skeleton-application", "description": "Skeleton Application for ZF2", "license": "BSD-3-Clause", "keywords": [ "framework", "zf2" ], "homepage": "http://framework.zend.com/", "require": { "php": ">=5.3.3", "zendframework/zendframework": ">2.1.3", "doctrine/doctrine-orm-module": "0.*" } }
3. Install it
php composer.phar self-update && php composer.phar install
4. Create an Album module with structure entity like the following :
5. Configure doctrine connection
You can define it at one file, but separate it with two file(local and global) can make security happy 😀
a. config/autoload/doctrine.global.php
//config/autoload/doctrine.global.php return array( 'doctrine' => array( 'connection' => array( 'orm_default' => array( 'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver', 'params' => array( 'host' => 'localhost', 'port' => '5432', 'dbname' => 'zftutordoctrine', ), ), ) ));
b. config/autoload/doctrine.local.php
//config/autoload/doctrine.local.php return array( 'doctrine' => array( 'connection' => array( 'orm_default' => array( 'driverClass' => 'Doctrine\DBAL\Driver\PDOPgSql\Driver', 'params' => array( 'user' => 'developer', 'password' => '123456', ), ), ) ));
6. register Album\Entity into doctrine driver in module/Album/config/module.config.php
//module/Album/config/module.config.php return array( 'doctrine' => array( 'driver' => array( 'Album_driver' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array(__DIR__ . '/../src/Album/Entity') ), 'orm_default' => array( 'drivers' => array( 'Album\Entity' => 'Album_driver' ), ), ), ), );
7. Register modules into config/application.config.php
//config/application.config.php return array( 'modules' => array( 'Application', 'DoctrineModule', 'DoctrineORMModule', 'Album' ), // These are various options for the listeners attached to the ModuleManager 'module_listener_options' => array( 'module_paths' => array( './module', './vendor', ), 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php', ), ), );
8. Generate Time !
a. convert-mapping
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping --namespace="Album\\Entity\\" --force --from-database annotation ./module/Album/src/
it will export “annotation” mapping information into ./module/Album/src/
b. generate-entities
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ --generate-annotations=true
it will add setter/getter into entities.
and you will get the following entities AUTOMATICALLY :
Album\Entity\Album
<?php namespace Album\Entity; use Doctrine\ORM\Mapping as ORM; /** * Album * * @ORM\Table(name="album") * @ORM\Entity */ class Album { /** * @var integer * * @ORM\Column(name="id", type="bigint", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="SEQUENCE") * @ORM\SequenceGenerator(sequenceName="album_id_seq", allocationSize=1, initialValue=1) */ private $id; /** * @var string * * @ORM\Column(name="artist", type="string", length=255, nullable=true) */ private $artist; /** * @var string * * @ORM\Column(name="title", type="string", length=255, nullable=true) */ private $title; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set artist * * @param string $artist * @return Album */ public function setArtist($artist) { $this->artist = $artist; return $this; } /** * Get artist * * @return string */ public function getArtist() { return $this->artist; } /** * Set title * * @param string $title * @return Album */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } }
Album\Entity\Track
<?php namespace Album\Entity; use Doctrine\ORM\Mapping as ORM; /** * Track * * @ORM\Table(name="track") * @ORM\Entity */ class Track { /** * @var integer * * @ORM\Column(name="track_id", type="bigint", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="SEQUENCE") * @ORM\SequenceGenerator(sequenceName="track_track_id_seq", allocationSize=1, initialValue=1) */ private $trackId; /** * @var string * * @ORM\Column(name="track_title", type="string", length=255, nullable=true) */ private $trackTitle; /** * @var \Album\Entity\Album * * @ORM\ManyToOne(targetEntity="Album\Entity\Album") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="album_id", referencedColumnName="id") * }) */ private $album; /** * Get trackId * * @return integer */ public function getTrackId() { return $this->trackId; } /** * Set trackTitle * * @param string $trackTitle * @return Track */ public function setTrackTitle($trackTitle) { $this->trackTitle = $trackTitle; return $this; } /** * Get trackTitle * * @return string */ public function getTrackTitle() { return $this->trackTitle; } /** * Set album * * @param \Album\Entity\Album $album * @return Track */ public function setAlbum(\Album\Entity\Album $album = null) { $this->album = $album; return $this; } /** * Get album * * @return \Album\Entity\Album */ public function getAlbum() { return $this->album; } }
JUST IMAGINE that YOU SHOULD WRITE THEM MANUALLY :p
9. Fill database tables rows, and Let’s call from whatever controller for testing :
public function indexAction() { $em = $this->getServiceLocator() ->get('doctrine.entitymanager.orm_default'); $data = $em->getRepository('Album\Entity\Track')->findAll(); foreach($data as $key=>$row) { echo $row->getAlbum()->getArtist().' :: '.$row->getTrackTitle(); echo '<br />'; } }
References :
1. Conversation with Anass Ans
1. http://docs.doctrine-project.org/en/2.0.x/reference/tools.html
2. http://wildlyinaccurate.com/useful-doctrine-2-console-commands
Thanks Samsonasik!!!
Was eagerly waiting for this post and it worked perfectly..
Keep posting this kind of stuff in future
Thanks…..
yes, insya Alloh, you’re welcome 😉
HI ,
i guess I have a simpler implementations , I wanted to share you
check out this gist : https://gist.github.com/tawfekov/4079388
just copy & change database config , and run it via cli , the only manual thing you need to is writing your own namespace
wow, thanks for sharing, i will take a look on that 😉
and I invite you to take a look @ https://github.com/tawfekov/ZF2EntityAudit , it provide a complete solution for doctrine2 auditing and let me know your ideas about it
ok, forked it, thanks 😉
hi…
I want to ask if there is a way to generate entities for a specific table of a database. eg. I want to generate entities for state table from db with also contains other more tables such as company, users,etc
Thanks…
try –filter=”Yourtablename”
Filter is not working. It says “No Metadata Classes to process.”
then you need to manually do it 😛
Hi samsonasik,
Sorry for my question that is not in this topic.
I would like to display a view from an action of a specific controller in another view of an action of a controller or layout in ZF2. In ZF1, we have $this->action plugin in view. Is there something similar in ZF2?
Thank you very much!
you can replace it by $this->render. for example :
and in another view : ( application/index/test.phtml ) you can call the var
The string ‘application/index/test’ is the template file? PhpRenderer automatically resolve it to test.phtml in view directory?
Thank you!
yes.
HI, I am working on zf2 and doctrine. And my DB is Oracle. Now when I am trying to generate the entities, it giving me error as “Table ACCOUNTS has no primary key. Doctrine does not support reverse engineering from tables that don’t have a primary key.”. So now my question is that whether is it possible to generate entities for table who doesn’t have primary key?
i have no idea, but i think primary key is what you must have when define a table.
can you create a class that extends the entity, where can I create new methods to be able to call on different controllers? because I do not want to duplicate code.
example:
“AlbumGateway extends Entity Album”
implements an automatically:
– GetRepository (‘Album\Entity\Album’)
– GetServiceLocator()->get(‘doctrine.entitymanager.orm_default’)
in a controller:
$album = new AlbumGateway ();
$return = $album->getSomething(“some_param”);
I think this way would be simpler and faster to development
I’ve been trying to implement this but I did not succeed, lack of knowledge
what do you think?
read my service manager cheat sheet : https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
Hi,
i’m having trouble using this cmd with windows :
/vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ –generate-annotations=true
i replace Album by my own module but still not works cause it’s not an internal or external cmd or exe file 😡
for note, “/vendor” as your type should be “./vendor” with adding “.” as prefix. if you’re using windows powershell, it should be work.
other way, try to change “/” (slash) with “\” (backslash), absolute path is better.
[…] 装好Doctrine之后,可以自动生成Entity,tutorial: E:zf_workplaceintranet>php /zf_workplace/intranet/vendor/doctrine/doctrine-module/bin/doctrine-module.php orm:convert-mapping –namespace=”Album\Entity\” –force –from-database annotation ./module/Album/src/ […]
Great, but how can we make a crud with this relation?
For example how to populate a combobox with categories and to save for some product?
Can you make an example?
Thank you.
Thanks samsonasik. It is very simple and very useful tutorial. Only 1 change I have to made during execution(as I was getting exception (Parse error: syntax error, unexpected T_NS_SEPARATOR, expecting T_STRING)
original line:
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=”Album\\Entity\\” –force –from-database annotation ./module/Album/src/
modified line:
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=Album\Entity\ –force –from-database annotation ./module/Album/src/
Regards,
Amit Dangwal
Thanks 😉
Hi,
Thanks for this very good tutorial.
I wondered how to extend generated entities, in order to be still able to regenerate at any time.
Simple example: on a User class, you have for instance firstname and lastname, and you need a new method such as getFullName() { return $this->firstname.’ ‘.$this->lastname; }
If you put this method in your entity, you will erase it the next time you want to generate entities. If you extends User, in ExtendedUser for example, you won’t be able to find your ExtendedUser using the Entity Manager.
What would you recommend?
Thanks
I recommend to generate if just necessary :). Typing is good 🙂
what if you have different modules and you need to generate some entities for one module, other entities for another module, and so on?
for some table, try –filter=”Yourtablename” , I have no idea for filtering complex like that, maybe create your own script to get it done 😉
I have this error when convert-mapping
PHP Fatal error: Uncaught exception ‘RuntimeException’ with message ‘Options with name “Caisse_driver” could not be found in “doctrine.driver”.’ in /home/ahmed/Desktop/test/vendor/doctrine/doctrine-module/src/DoctrineModule/Service/AbstractFactory.php:81
I Want Search the table data in webpage…?? i want to implement the search field in my project ..i download doctrinesearch using this url..
Thanks for sharing this code. It is very useful..
I have a similiar scenario as yours but have some issues in adding a tracker. I have two many-to-one releationship entities: Album(1) and Tracker(m).
My code is like this:
$tracker = new Tracker();
$tracker->album = constrcuctAlbumfromDB();
$em->persist($tracker);
$em->flush()
This would result error:
‘ that was not configured to cascade persist operations for entity: \album@00000000349002ee00000000c955fd11. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={“persist”}). If you cannot find out which entity causes the problem implement ‘Album#__toString()’ to get a clue.
After I add cascade={“persist”} for $album in tracker, The error disappear, but the problem is a new tracker is insert each time i added a tracker. THis is not expected.. What I want is only to insert a tracker, album_id of it points to existing album record..
Thanks for help.
Hi everybody,
I followed all step; but have an issues on orm:generate-entities with message:
No Metadata Classes to process.
orm:convert-mapping wokrs fine, and files create on Entity folder.
Have you idea ?
Thanks very much
I have same problem , one year later…Coencidence
Thanks for the post. But…
Here same problem….
No Metadata Classes to process.
I try with “doctrine/doctrine-orm-module”: “0.8.*”, and “doctrine/doctrine-orm-module”: “0.*”, and “doctrine/doctrine-orm-module”: “dev-master”, but not luck.
Then I try
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.”/src”), $isDevMode, null, null, false);
and still No Metadata Classes to process.
Some advice?
Thanks a lot!
Try this answer http://stackoverflow.com/a/18469048/1335142.
This will be create all entities and you can copy-past entity which you need.
I have a one form and i have two entity..if i pass one form value that will stored in two tables(entity)..can u help me..
just code it! or use trigger
I have two tables like role,rolerights i want to add the data in both table in single form i have one controller, one PHTML(add.phtm),two entity(role,rolerights),one form(role),,where i write the query ??
Good Job! Tanks a lot!
I get this error…
Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\ServiceNotFoundException’ with message ‘Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.cli’ in /Users/bla/Sites/bla/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:495
Thanks in advance!
Peter did you found a solution? I have the same issue!
HI I have a problem…. i’ve follow all the instructions but in generate time i got an error
I’ve entered this in command
doctrine-module orm:convert-mapping –namespace=”Album\\Entity\\” –force –from-database annotation ./module/Album/src/
and I got an error
[PDOException]
could not find driver
Was is because I dont have the track table?
The files I have is from the skeleton from zend, it has already the album add edit delete tutorial,
and I want to switch it to doctrine orm instead of zend db….
Are you using PostgreSQL? If not, you’ll need to tweak the configuration a bit.
I was using MySQL, so my config ended up looking like this:
array(
‘doctrine’ => array(
‘connection’ => array(
‘orm_default’ => array(
// driverClass has changed to PDOMySql\Driver
‘driverClass’ => ‘Doctrine\DBAL\Driver\PDOMySql\Driver’,
‘params’ => array(
‘host’ => ‘localhost’,
‘port’ => ‘3306’,
‘dbname’ => ‘DB_NAME’,
‘user’ => ‘USER’,
‘password’ => ‘PASS’,
),
),
)
));
I’ve able to solve the problem by merging the doctrine.global.php and doctrine.local.php and put it in global.php… i dont know why
Hey man, thank you so much!
Thanks!!! Great THANKS MASTER!
Hi, follow your tutorial. I have a table named agence. when write :
$objectManager = $this->getServiceLocator()->get(‘Doctrine\ORM\EntityManager’);
$agences = $objectManager->getRepository(‘Application\Entity\TAgence’)->findAll();
I got this as error
Additional information:
Doctrine\DBAL\DBALException
File:
C:\xampp\htdocs\isigt\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:91
Message:
An exception occurred while executing ‘SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t0’:
SQLSTATE[42P01]: Undefined table: 7 ERREUR: la relation « t_agence » n’existe pas
LINE 1: …t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t…
^
Any idea?
Here is the query produced
SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t0
And I want that query
SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM “t_Agence” t0
This is a good tutorial but can you tell me how you will make the “createAction()” for the album?
https://github.com/shanethehat/zf2-doctrine-tutorial
[…] site: https://samsonasik.wordpress.com/2013/04/10/zend-framework-2-generate-doctrine-entities-from-existing… […]
when i call the similar get method of the child entity like $row->getAlbum()->getArtist() in our case i get error
An exception occurred while executing ‘SELECT t0.group_id AS group_id1, t0.group_name AS group_name2, t0.group_desc AS group_desc3, t0.group_image AS group_image4, t0.created_by AS created_by5, t0.created_date AS created_date6, t0.is_active AS is_active7 FROM group t0 WHERE t0.group_id = ?’ with params [1]:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘group t0 WHERE t0.group_id = 1’ at line 1
check your table relation and param passing
check you entity relation and parameter query
Hello sire,
How to do with CLi to generate just a specific entity from DB ?
try try –filter=”Yourtablename”
Hi,
Are you able to generate entity for single table using –filter option?
If Yes, Could you please let me know the Version ZF2 and Doctrine that you are using?
I tried –filter option but still it generates entities for all the table.
Hi,
I haven’t executed all the steps however I just noticed that 3rd point “Install it” is displaying HTML as it is on the screen. I have firefox V-28 browser.
I guess that was happening because of some temporary issue. After refreshing few times it went away.
hi Malik, thank for great post!! I’m wondering how can we access Track from Album? Something like this:
$tracks = $album->getTracks();
foreach ($tracks as $track) {..blah blah…}
Do we need to add some more lines like this in Album:
/**
* @var Collection
*
* @ORM\OneToMany(targetEntity=”\Album\Entity\Track”, mappedBy=”album”))
* @ORM\JoinColumns({
* @ORM\JoinColumn(name=”id”, referencedColumnName=”album_id”)
* })
*/
private $comment_metas;
if you already related tables correctly, personally i think generate only is enough
Hi Samsonasik
I got an error:
[Doctrine\Common\Annotations\AnnotationException]
[Semantical Error] The annotation “@ORM\Table” in class Application\Entity\Album was never imported. Did you maybe forget to add a “use” statement for this a
nnotation?
when I run ‘./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Application/src/ –generate-annotations=true’
no, you are not follow one or two step, and if you’re using windows, please using windows powershell
Hi there,
Thanks a lot for detailed post. I am able to generate entities for mySQL database table.
I am not sure if this is my mistake or something else but when I ran “convert-mapping” and “generate-entities” commands application has generated entities for all the database tables.
I have also tried these commands using “–filter” option however it didn’t helped.
Could you please help me out of this situation? because my application is already built in symfony 1.X and we are moving it into ZEND Framework 2 so I wanted to generate entities for single table at a time.
Thanks once again for the post.
[…] we are using Doctrine2 in Zend Framework 2 project, we can use existing module named DoctrineModule that can be used to easist our job. Now I will explain about how to use […]
Assalamualaikum, Selamat menyambut Ramadhan yang bakal tiba. Pertama nya tahniah posting yang hebat2 dari Tuan.
Saya ada masalah sedikit disini, apabila saya run command seperti yang diberikan dalam contoh diatas saya dapat return error seperti berikut :
‘”@php_bin@”‘ is not recognized as an internal or external command, operable program or batch file.
minta bantuan… apa agaknya punca masalah saya ini.
m.zam
N9.MY
Wa’alaikumsalam, coba set path php.exe atau path nya php bin, register ke system path, coba google
Terima kasih, tapi path untuk php.exe memang telah di set dari awal tetapi masih error..
contoh path saya >>>
D:\developer\xampp\htdocs\bukukira>path
PATH=C:\Windows\system32;D:\developer\xampp\php;C:\ProgramData\ComposerSetup\bin;
C:\Users\User\AppData\Local\Android\android-studio\sdk\platform-tools\;D:\developer\xampp\php
cuma ‘php bin’ @ ‘..\php\bin’ @ php_bin memang tiada dalam computer saya .. saya install PHP yang datang sekali dengan XAMMP.
Dear samsonasik , the article is great, i liked a lot, thanks.
But I am have a problem, when doctrine is create entities, the first line, refer to namespace is generate namespace Livraria\Entity\; when correct is namespace Livraria\Entity;
Do you kwnow how i solve this question? Thanks
that’s weird, maybe change the “doctrine/doctrine-orm-module” version to “0.8.*” ?
Thank you so much!
let’s say i have 7 tables in my db and i want to create entities for only one table say user table then what to do ?
try –filter=”Yourtablename” , please see other comment.
while doing generating entities referring to 8.b cmd .resulting no metadata classes to process. can you help me.
try to use doctrine-orm-module version 0.8.*
My friend,
I have a field in oracle “date = TIMESTAMP (6)” as I insert it using new \ Datetime () ?? I’ve tried several ways.
Thank you
Hi Samson,
Great post Malik…
I am learning Zend 2 by following all your posts one by one.But now i got stuck at this stage..Hope you would
help..Could you please explain the steps “”
a. convert-mapping
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=”Album\\Entity\\” –force –from-database annotation ./module/Album/src/
b. generate-entities
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ –generate-annotations=true
i tried runing in ssh terminal like this:
php ./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ –generate-annotations=true
but it gives me “coulnt open input file /vendor/doctrine/doctrine-module/bin/doctrine-module …” error ..
Please help so that i could continue to learn from your posts..Thanks
there is no “/vendor/doctrine/doctrine-module/bin/doctrine-module’ file then, try adding “.” before “/vendor”.
actually, it’s really depend on the os you’re using, if you use windows command prompt, it should use backslash instead of slash, you should can use slash with windows powershell i think, and full path is the way to check it. if you doubt about using command shell, you can learn first for it http://linuxcommand.org/learning_the_shell.php
Thanks for quick reply.
Assalam o Aliakum samson..
Resolved…! just a quick one.
I am new to Zf2 and doctrine ORM.if we have got database with large number of tables lets say 40 tables (30 main tables,10 child tables to interpret many to many relationship),Does it mean that we will need to create 30 entities under (Modulename/src/Modulename/Entity)..Is there anyway we could map more than one table in the same Entity file. Any cheat/tip?I would appreciate if you could explain this with quick example or tutorial..
Thanks
JazakAllah
yes, use 30 entities. look doctrine doc
Hi ,
A very interesting post…Well done..
One issue :
$data = $em->getRepository(‘Album\Entity\Track’)->findAll();
is getting all the results from Track but don’t think the function is not mapped correctly.
In my controller action.. i have used your instructions like this:
foreach ($data as $key => $row) {
echo $data->getAlbum()->getArtist() . ‘::’ . $row->getTrackTitle();
echo ”;
}
I am getting this error in this part:
“Call to a member function getAlbum() on a non-object “..
Any fix/help?
pleae compare your code with my post, $data should be $row.
Hello,
Is possibly to generate entirely the form for One-To-Many relation using solely annotations ?
I have a sample case posted and it seems none has knowledge about this situations:
http://stackoverflow.com/questions/19529392/zf2-form-with-annotation-fieldset-not-validating#27784997
i have no idea for that
Somehow my stackoverflow post dissapeared (so may not seen the details), I reposted here:
http://zend-framework-community.634137.n4.nabble.com/One-To-many-associations-and-forms-based-entirely-on-annotations-td4662414.html
Fantastic post!!!! Thank you so much
Thanks! you save me.
Thank you so much
Hi man. I can just connect to external schema. How can I do it?
That helped me a lot! But I can not use entities generate . always arises
File mapping drivers must have a valid directory path, however the given path [/Applications/MAMP/htdocs/my_app/module/Application/config/../src/Application/Entity] seems to be incorrect!
I added the Album module correctly and used vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ –generate-annotations=true
Can you help me?
did you try using absolute path in config? are you really sure the Entity folder exists ? are you really sure about directory permissions ?
I realized that was wrong in the driver. Mine was with the following configuration:
‘doctrine’ => array (
‘driver’ => array (
__NAMESPACE__. ‘_driver’ => array (
‘class’ => ‘Doctrine \ ORM \ Mapping \ Driver \ AnnotationDriver’
‘cache’ => ‘array’
‘paths’ => array (
__DIR__. ‘/../src/’. __NAMESPACE__. ‘/ Model’
)
)
‘orm_default’ => array (
‘drivers’ => array (
__NAMESPACE__. ‘\ Model’ => __NAMESPACE__. ‘_driver’
)
)
)
)
I used that suggested and it worked. thanks
nice 😉
I have generated entity and added setter/getter into entities.
with commands
a. convert-mapping
b. generate-entities
But can not able to automatically add Joins annotations in entity
Ex:
/**
* @var \Admin\Entity\Merchants
*
* @ORM\ManyToOne(targetEntity=”Admin\Entity\Merchants”)
* @ORM\JoinColumns({
* @ORM\JoinColumn(name=”merchant_id”, referencedColumnName=”merchant_id”, nullable=true)
* })
*/
did you set up the db relation correctly?
Hello!
I need generate Entities from DB without console.
I found how generate-entities without console (http://docs.doctrine-project.org/en/latest/reference/tools.html). But, I need to convert mapping from DB(a specific table of DB) without use console for the next step (generate-entities).
Please, tell me, how I can do it.
P.S. sorry for my bad english.
i guess you need to consult the code for that 😛
After digging around, I got a solution to the “No Metadata Classes to process” problem.
The issue is with the Annotation metadata driver that Doctrine uses to read the entity classes.
The driver uses a default “SimpleAnnotationReader” to do this and it isn’t compatible with the Entities the way they are setup.
Solution:
1. Create a cli-config.php file in your application config folder.
// cli-config.php
require_once ‘bootstrap.php’;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
return ConsoleRunner::createHelperSet($entityManager);
2. Create the bootstrap.php file in the same directory to be used by the cli-config.php file.
‘pdo_mysql’,
‘user’ => ‘username’,
‘password’ => ‘password’,
‘dbname’ => ‘dbname’
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false);
$entityManager = EntityManager::create($dbParams, $config);
3. Use vendor/bin/doctrine instead of ./vendor/doctrine/doctrine-module/bin/doctrine-module to access the Doctrine console optons.
Because we need to bypass Doctine’s default way of connecting to the db and reading entity annotations, we must define our very own custom method of doing both.
The bootstrap.php contains dsn connection parameters to connect to the database (I use MySQL) and more importantly, a custom call to the Annotation metadata configuration method: createAnnotationMetadataConfiguration. The method takes 5 arguments. The important change is in the fifth argument – “$useSimpleAnnotationReader” boolean. Changing this to false forces doctrine to read from the Entities directory to find annotations.
Hope someone finds this helpful.
Nice, 5 Years later you saved me a lot of research. Thanks man 😀
I want to create an entity to an existing project for a single database. I use –filter option,
./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=”Application\\Entity\\” –force –from-database –filter=”user__file_user__file_tags_linker” annotation ./module/Application/src/
but got error:
[Doctrine\ORM\Mapping\MappingException]
Property “language” in “Application\Entity\Appointment” was already declared, but it must be declared only once
The table has nothing to do with appointments and there is also no Entity for Appointment.
What do you think, what I am doing wrong?
greetings from germany
Martin
Hi, I’ve no idea, sorry…
Thank you very much for your post.
I succeeded in importing a project with more than 150 tables using this tutorial.
Only four of its foreign keys were not imported.
But I am still in doubt if I will upgrade from version 1 of doctrine to version 2.
It would help me a lot if there would be some way not to change the names of the attributes from my_attribute to myAttribute, as it does. Although my project changes the names of the related entities as it does.
Do you know of some way of doing this?
cool. Sorry, I don’t have idea with doctrine 1
Fatal error: Uncaught exception ‘Zend\ModuleManager\Exception\RuntimeException’ with message ‘Module (Application) could not be initialized.’ in C:\wamp\www\private\vendor\zendframework\zend-modulemanager\src\ModuleManager.php on line 203
Zend\ModuleManager\Exception\RuntimeException: Module (Application) could not be initialized. in C:\wamp\www\private\vendor\zendframework\zend-modulemanager\src\ModuleManager.php on line 203
Call Stack:
0.0000 226720 1. {main}() C:\wamp\www\private\vendor\doctrine\doctrine-module\bin\doctrine-module:0
0.0010 238984 2. include(‘C:\wamp\www\private\vendor\doctrine\doctrine-module\bin\doctrine-module.php’) C:\wamp\www\private\vendor\doctrine\doctrine-module\bin\doctrine-module:4
0.0150 1066592 3. Zend\Mvc\Application::init() C:\wamp\www\private\vendor\doctrine\doctrine-module\bin\doctrine-module.php:53
0.0440 2282920 4. Zend\ModuleManager\ModuleManager->loadModules() C:\wamp\www\private\vendor\zendframework\zend-mvc\src\Application.php:272
0.0440 2283112 5. Zend\EventManager\EventManager->triggerEvent() C:\wamp\www\private\vendor\zendframework\zend-modulemanager\src\ModuleManager.php:120
0.0440 2283432 6. Zend\EventManager\EventManager->triggerListeners() C:\wamp\www\private\vendor\zendframework\zend-eventmanager\src\EventManager.php:251
0.0450 2305792 7. call_user_func:{C:\wamp\www\private\vendor\zendframework\zend-eventmanager\src\EventManager.php:490}() C:\wamp\www\private\vendor\zendframework\zend-eventmanager\src\EventManager.php:490
0.0450 2305960 8. Zend\ModuleManager\ModuleManager->onLoadModules() C:\wamp\www\private\vendor\zendframework\zend-eventmanager\src\EventManager.php:490
0.0450 2306888 9. Zend\ModuleManager\ModuleManager->loadModule() C:\wamp\www\private\vendor\zendframework\zend-modulemanager\src\ModuleManager.php:97
0.0450 2307040 10. Zend\ModuleManager\ModuleManager->loadModuleByName() C:\wamp\www\private\vendor\zendframework\zend-modulemanager\src\ModuleManager.php:175
use ZendSkeletonApplication, you will get Application module by default, and please follow the zf2 doc for getting started first.
Hi, i have followed your tutorial and the 2 entites have joined and its working perfect. but i am having an issue, on saving data, the attribute which i used for relationing is not primary key, so its not being saved while saving data form.
e.g
table 1 = id, topic
table 2 = id, comment, user_id, topic_id
table 3 = id, user_name
now on updating or inserting values in table 2, i can’t update\add user_id and topic_id unless i remove join from Entity
that is basic of table relation ( master – detail )
[…] Zend Framework 2 : Generate Doctrine Entities from Existing Database using DoctrineModule and Doctri… […]
Thanks for your post.
How can I set table pfrefix fo my project?
you can google : “doctrine add table prefix”