Clean way to get foreign key objects in PHP MySQL query

一笑奈何 提交于 2019-12-12 16:24:59

问题


I use the following code to get a book object from my MySQL database.

$q = $pdo->prepare('SELECT 
                        book_id "id", 
                        book_title "title", 
                        book_slug "slug"
                    FROM book 
                    WHERE book_id=:id');
$q->bindParam(':id', $id, PDO::PARAM_INT);
$q->execute();
$book = $q->fetchObject('Book');

Books have a many-to-many relation to songs, which have a song_id, song_title and song_lyrics, so I have a book_song table with book_id and song_id.

I'd like to get all the songs belonging to a book. Is there a clean way to do this in one query?

What I'm looking for here is how to write the query in a clean way and also how to process the results to end up with a Book object which has an array of Song objects without too much code.


回答1:


The JOIN that gillyspy suggested would be how an ORM would handle this, but if you're using just PDO, then you have to handle all the mappings yourself (and the looping, and detecting when to create a new object, etc.) This looks to me like you've crossed the threshold where it makes sense to consider an ORM framework (such as http://www.phpactiverecord.org/). If you add even one more one-to-many association, the mappings are going to make your brain hurt.



来源:https://stackoverflow.com/questions/16524230/clean-way-to-get-foreign-key-objects-in-php-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!