Featured Post

Integrating FirePHP with Zend Framework 2

In this post I will show you how to easily integrate FirePHP – Mozilla Firefox extension with Zend Framework 2. FirePHP enables you to log to your Firebug Console using a simple PHP method call. All data is sent via response headers and will not interfere with the content on your page. FirePHP...

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: , , , , , , ,

0

Introduction

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.

/module/Album/view/album/album/index.phtml

Now create templates for song table as follow.

/module/Album/view/album/song/add.phtml:

/module/Album/view/album/song/edit.phtml:

/module/Album/view/album/song/index.phtml:

/module/Album/view/album/song/delete.phtml:

As always you can grab all the code from GitHub:
https://github.com/evolic/zf2-tutorial/tree/v0.3.3.

Write a comment