简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM