Featured Post

Mozilla Firefox addons

Many of you probably use Mozilla Firefox, I can’t imagine that you haven’t heard about that browser at all. What I want to speak about is Add-ons, by big A, because add-ons themselves are the biggest feature and power of the Firefox. I will focus on the two kind of add-ons: Must have –...

Read More

Creating one to many relation in Doctrine 2 ORM

Posted by Tomasz Kuter | Posted in Programming, Web development | Posted on 23-03-2013

Tags: , , , , , , ,



In this tutorial I will present relational mapping between albums and songs.
In Zend Framework 2 Tutorial we had only one table – it was called albums, and stored albums data.

Today we will extend our sample application with new table – songs.
Each album can has many songs, but single song can be connected to only one album.
It is called relation OneToMany in Doctrine ORM.

Update your database with following:

Updating the code

At the beginning we need to update Album module configuration with new controller and route details:

Doctrine entities

First things to do is to update our entities: update Album entity and add new for Songs.

Updated Album entity, stored in file /module/Album/src/Album/Entity/Album.php should be updated with:

In above code we created a relation between old Album, and new Songs entities. Each album could have many songs, but single song could have relation only to one album – it is quite simple.

Now add Songs entity (/module/Album/src/Album/Entity/Song.php):

Update Composer configuration

In this tutorial we start using Loculus library, so we need to update the Composer settings:

And update vendor libraries:

Updating controllers

Updated Album controller should look like (/module/Album/src/Album/Controller/AlbumController.php):

And songs controller (/module/Album/src/Album/Controller/SongController.php):

In edit action song entity is loosing relation to album, because of the $form->bindValues(), so it was fixed in dirty way for now. Case need more investigation in future.

Updating forms

Here is Zend\Form configuration for Song table. Create file /module/Album/src/Album/Form/SongForm.php according to following code:

Updating models

It is time to take care our models. At first we need to take care about Album model code (/module/Album/src/Album/Model/Album.php):

and song model (/module/Album/src/Album/Model/Song.php):

Updating .phtml templates

Last thing is .phtml templates update.


Now create templates for song table as follow.





As always you can grab all the code from GitHub:

Write a comment