开发者

Creating a DAO Query with many One-to-Many Relationships?

I am developing a web application with PHP and MySQL. I have an entity named, User, that has many one-to-many relationships (with other objects) within it (list of Addresses, list of Emails, list of PhoneNumbers, etc). These many addresses, emails, phone numbers are supplied to the user via junction tables in the database (user_link_addresses, user_link_emails, etc).

I am now trying to create an efficient DAO for the User entity, specifically methods readUserById($userId) and readAllUsers(). However, since I am an amateur at sql and the DAO pattern, I am having trouble creating this DAO correctly.

I have been told that it is important for network efficiency to keep your DAO to one query that reads all the information at once and then can be 开发者_如何学编程mapped to that entity accordingly. That does make sense, but I am having trouble generating one query that has the necessary information from everything and that can be mapped correctly to my entity.

Right now, I can get this information by performing multiple queries within a loop after getting the users... I just don't like that idea (and I'm sure it's not correct). Also, I know how to do joins with junction tables - just not with something this complex and that needs to be mapped correctly as well.

TABLE NAMES AND FIELDS

TABLE: user FIELDS: user_id, username, password

TABLE: address FIELDS: address_id, street, city, state, zip_code, type

TABLE: email FIELDS: email_id, email, type

TABLE: phone_number FIELDS: phone_number_id, area_code, phone_number, type

-- JUNCTION TABLES FOR ASSOCIATIONS --

TABLE: user_link_address FIELDS: user_id, address_id

TABLE: user_link_email FIELDS: user_id, email_id

TABLE: user_link_phone_number FIELDS: user_id, phone_number_id

Anyway, all help is greatly appreciated,

Steve


Sometimes it's worth it to include associations within queries and sometimes it's not. There's a really neat plugin for Ruby on Rails that analyzes your application as it runs and tells you which queries should include associated models.

You could try something like:

SELECT *
    FROM `user` 
    INNER JOIN `user_link_addresses`
        ON `user`.id = `user_link_addresses`.user_id
    INNER JOIN `user_link_foo`
        ON `user`.id = `user_link_foo`.user_id

If you tell me all your table names and fields, I could help you write a more specific query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜