I guess this is a common Problem:
- consider an application where Users have a Role
You will likely have something like
User
username : String
role : String
but in your database you have
CREATE TABLE IF NOT EXISTS roles (
role_id TINYINT(1) UNSIGNED AUTO_INCREMENT,
role_name VARCHAR(10) NOT NULL,
PRIMARY KEY(role_id),
) ENGINE=InnoDB
and
CREATE TABLE IF NOT EXISTS users (
username VARCHAR(20),
role_id TINYINT(1) UNSIGNED NOT NULL
PRIMARY KEY(username)
INDEX idx_role (role_id)
CONSTRAINT fk_user_role
FOREIGN KEY idx_role (role_id) REFERENCES roles(role_id)
) ENGINE=InnoDB
What I would like to know is:
What would be the most appropriate approach of creating the User model instance from the database and why?
While this seems to be a trivial and basic problem, I can think of five ways of doing this:
- Query Users and Roles and merge results in a Datamapper into a User instance
- Join Roles on User in Query and map Role name to User role property in a Data Mapper
- Create User from query and lazy load (with caching) the Role name when it's needed
- Preload and cache all Roles to a Repository on App start and look them up when needed
- Hardcode Roles into a Enum-like class in the App instead of the DB
Thanks!