Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Generate Doctrine Entities from Existing Database using DoctrineModule and DoctrineORMModule

Posted in orm, Teknologi, Tutorial PHP, Zend Framework 2 by samsonasik on April 10, 2013

zf2-zendframework2If 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-albumomodule-structure
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

110 Responses

Subscribe to comments with RSS.

  1. Mohammad Nomaan Patel said, on April 11, 2013 at 5:03 pm

    Thanks Samsonasik!!!

    Was eagerly waiting for this post and it worked perfectly..

    Keep posting this kind of stuff in future

    Thanks…..

  2. tawfek daghistani said, on April 12, 2013 at 4:28 pm

    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

  3. Mohammad Nomaan Patel said, on April 12, 2013 at 6:09 pm

    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…

    • samsonasik said, on April 12, 2013 at 7:30 pm

      try –filter=”Yourtablename”

      • Iftikhar Ahmad said, on August 21, 2015 at 1:02 pm

        Filter is not working. It says “No Metadata Classes to process.”

      • samsonasik said, on August 22, 2015 at 3:42 am

        then you need to manually do it 😛

  4. Khiem said, on April 14, 2013 at 7:08 pm

    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!

    • samsonasik said, on April 14, 2013 at 8:00 pm

      you can replace it by $this->render. for example :

        echo $this->render('application/index/test', array('var' => 'value')); 
      

      and in another view : ( application/index/test.phtml ) you can call the var

      echo $var; 
      
      • Khiem said, on April 14, 2013 at 9:28 pm

        The string ‘application/index/test’ is the template file? PhpRenderer automatically resolve it to test.phtml in view directory?
        Thank you!

      • samsonasik said, on April 14, 2013 at 11:39 pm

        yes.

  5. Qubess Ali said, on April 18, 2013 at 8:59 pm

    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?

    • samsonasik said, on April 19, 2013 at 5:35 am

      i have no idea, but i think primary key is what you must have when define a table.

  6. Thomas Sens said, on April 20, 2013 at 3:58 am

    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?

  7. Angus said, on April 25, 2013 at 4:52 pm

    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 😡

    • samsonasik said, on April 25, 2013 at 6:25 pm

      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.

  8. […] 装好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/ […]

  9. Vitor said, on June 18, 2013 at 11:35 pm

    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.

  10. Amit Dangwal said, on July 10, 2013 at 10:53 pm

    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

  11. Thomas Dutrion said, on July 12, 2013 at 1:44 am

    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

    • samsonasik said, on July 13, 2013 at 12:44 am

      I recommend to generate if just necessary :). Typing is good 🙂

  12. Johan said, on July 19, 2013 at 11:54 pm

    what if you have different modules and you need to generate some entities for one module, other entities for another module, and so on?

    • samsonasik said, on July 20, 2013 at 12:33 am

      for some table, try –filter=”Yourtablename” , I have no idea for filtering complex like that, maybe create your own script to get it done 😉

  13. Ahmed said, on August 6, 2013 at 4:45 pm

    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

  14. Ragunathan said, on August 29, 2013 at 5:53 pm

    I Want Search the table data in webpage…?? i want to implement the search field in my project ..i download doctrinesearch using this url..

  15. wodaxia said, on August 30, 2013 at 4:51 pm

    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.

  16. Jazz said, on September 8, 2013 at 9:01 am

    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

    • Leonardo Stringher said, on September 9, 2014 at 3:07 am

      I have same problem , one year later…Coencidence

      • Agustincl said, on May 20, 2015 at 7:21 pm

        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!

    • Sergiy Popov said, on February 7, 2016 at 5:17 am

      Try this answer http://stackoverflow.com/a/18469048/1335142.
      This will be create all entities and you can copy-past entity which you need.

  17. Bharath said, on September 11, 2013 at 8:31 pm

    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..

  18. Bharath said, on September 11, 2013 at 9:30 pm

    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 ??

  19. Thomas D said, on October 8, 2013 at 8:58 pm

    Good Job! Tanks a lot!

  20. Peter said, on October 22, 2013 at 1:32 pm

    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!

    • Daniela said, on October 28, 2013 at 8:12 pm

      Peter did you found a solution? I have the same issue!

  21. web2sign said, on November 19, 2013 at 9:08 am

    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….

    • Edan Schwartz said, on July 26, 2014 at 12:25 am

      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’,
      ),
      ),
      )
      ));

  22. web2sign said, on November 19, 2013 at 9:22 am

    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

  23. Marcos said, on November 20, 2013 at 10:19 am

    Hey man, thank you so much!

  24. Den said, on December 19, 2013 at 6:10 pm

    Thanks!!! Great THANKS MASTER!

  25. Youssoufou Yabré said, on January 24, 2014 at 10:42 pm

    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

  26. Pomirleanu Florentin Cristinel said, on January 29, 2014 at 9:08 pm

    This is a good tutorial but can you tell me how you will make the “createAction()” for the album?

  27. Zend framework 2 | docaohuynh said, on February 4, 2014 at 2:18 pm

    […] site: https://samsonasik.wordpress.com/2013/04/10/zend-framework-2-generate-doctrine-entities-from-existing… […]

  28. danishshres said, on March 21, 2014 at 8:27 pm

    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

  29. heronour said, on April 16, 2014 at 6:06 pm

    Hello sire,
    How to do with CLi to generate just a specific entity from DB ?

    • samsonasik said, on April 16, 2014 at 9:05 pm

      try try –filter=”Yourtablename”

    • moreyogesh said, on May 20, 2014 at 1:57 pm

      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.

  30. yogesh said, on April 16, 2014 at 7:17 pm

    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.

    • yogesh said, on April 16, 2014 at 7:19 pm

      I guess that was happening because of some temporary issue. After refreshing few times it went away.

  31. Pham said, on April 17, 2014 at 5:04 am

    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;

    • samsonasik said, on April 17, 2014 at 5:46 pm

      if you already related tables correctly, personally i think generate only is enough

  32. Leo said, on April 29, 2014 at 11:00 am

    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’

    • samsonasik said, on April 30, 2014 at 7:12 pm

      no, you are not follow one or two step, and if you’re using windows, please using windows powershell

  33. moreyogesh said, on May 19, 2014 at 9:21 pm

    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.

  34. […] 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 […]

  35. mohammad zam zam said, on June 26, 2014 at 1:42 pm

    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

    • samsonasik said, on June 27, 2014 at 2:53 am

      Wa’alaikumsalam, coba set path php.exe atau path nya php bin, register ke system path, coba google

      • mohammad zam zamm said, on June 27, 2014 at 9:01 am

        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.

  36. Euller Cristian said, on September 22, 2014 at 7:53 am

    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

    • samsonasik said, on September 24, 2014 at 12:17 am

      that’s weird, maybe change the “doctrine/doctrine-orm-module” version to “0.8.*” ?

  37. Jo said, on September 23, 2014 at 4:36 pm

    Thank you so much!

  38. jangya said, on September 25, 2014 at 1:41 pm

    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 ?

    • samsonasik said, on September 25, 2014 at 11:14 pm

      try –filter=”Yourtablename” , please see other comment.

  39. jangya said, on September 25, 2014 at 1:50 pm

    while doing generating entities referring to 8.b cmd .resulting no metadata classes to process. can you help me.

  40. bgastaldi said, on October 24, 2014 at 1:40 am

    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

  41. Shimmy Sethi said, on November 26, 2014 at 12:29 am

    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

    • samsonasik said, on November 26, 2014 at 5:01 am

      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

  42. Shimmy Sethi said, on November 26, 2014 at 3:50 pm

    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

  43. Sweety Kh said, on November 26, 2014 at 11:27 pm

    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?

    • samsonasik said, on November 27, 2014 at 1:54 am

      pleae compare your code with my post, $data should be $row.

  44. cbichis said, on January 13, 2015 at 4:40 am

    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

  45. Julián Gorge said, on January 23, 2015 at 12:31 pm

    Fantastic post!!!! Thank you so much

  46. André Paulena said, on February 23, 2015 at 2:05 am

    Thanks! you save me.

  47. Luiz said, on March 4, 2015 at 2:29 am

    Thank you so much

  48. Alesson Evangelista said, on July 2, 2015 at 1:14 am

    Hi man. I can just connect to external schema. How can I do it?

  49. Manoel Filho said, on July 19, 2015 at 2:57 am

    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?

    • samsonasik said, on July 21, 2015 at 3:49 pm

      did you try using absolute path in config? are you really sure the Entity folder exists ? are you really sure about directory permissions ?

  50. Manoel Filho said, on July 25, 2015 at 4:59 am

    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

  51. Vaishnavesh said, on August 28, 2015 at 4:54 pm

    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)
    * })
    */

  52. Igor said, on September 1, 2015 at 12:14 pm

    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.

  53. Akin Williams said, on September 13, 2015 at 1:54 am

    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.

    • steasenburger said, on May 6, 2019 at 9:32 pm

      Nice, 5 Years later you saved me a lot of research. Thanks man 😀

  54. Martin said, on November 27, 2015 at 2:49 am

    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

  55. Almir Duarte said, on December 12, 2015 at 11:57 am

    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?

  56. tokkto said, on May 15, 2016 at 10:42 am

    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

    • samsonasik said, on May 16, 2016 at 2:34 am

      use ZendSkeletonApplication, you will get Application module by default, and please follow the zf2 doc for getting started first.

  57. nabeel ahmed said, on July 8, 2016 at 4:29 am

    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

  58. […] Zend Framework 2 : Generate Doctrine Entities from Existing Database using DoctrineModule and Doctri… […]

  59. Nguyen said, on September 22, 2020 at 5:22 pm

    Thanks for your post.

    How can I set table pfrefix fo my project?


Leave a comment