Create a lookup table with Doctrine2

时间:2016-03-02 10:53:24

标签: php doctrine-orm

I have recently installed Doctrine2 on my web server and all works great. I have setup all my entities but now I'm at the point where I want to create a lookup table and I'm a bit confused how to do that. I want a table which looks like this:

tbl_Role                       tbl_User
+--------+----------+          +--------+----------+--------------+----------+
|   id   |   Name   |          |   id   |   Name   |   Password   |   Role   |
+--------+----------+          +--------+----------+--------------+----------+
|   1    |   Admin  |
|   2    |   User   |
|   3    |   Free   |
+--------+----------+

Between the Role and the User table consists a OneToMany relation (one Role has many Users) and this table does not change in future. I do not want to use Enums because of the update or reorder problem with them (if nevertheless something changed)

My question now is how I can represent this lookup table as a Doctrine entity? Normally if I want to create a new User I have to get the fitting Role from the DB and set it as a reference in the User entity. This seems a bit expensive to me. It would be great if I could have only the Role IDs in static PHP fields so I can set them as reference for the User. Is this possible?

Another problem is how I get the lookup values into the database. Can I implement a method into the Role entity itself which is executed after the Role table is created? This way it would be possible to mark the constructor as private and all values are present after a migration.

1 个答案:

答案 0 :(得分:1)

First of all, it won't be too expensive, because Doctrine2 has a few cache layers and these queries will be efficiently cached since the Role table won't change.

Anyway, if Role table won't change, I'm not sure if it should be kept in database. You could create a "static" factory service for it to create simple value objects as a part of your domain layer.