title: Best Practice approach to relating MySQL join queries to OOP and Objects
body: <p>I'm working on a PHP web application where users can create trips to destinations, and invite other users on these trips.</p>
  
  <p>I have MySql tables for <code>Destinations</code>, <code>Trips</code>, and <code>Users</code>, and a table called <code>Invites</code> to resolve the many-to-many relationship between <code>Users</code> and <code>Trips</code>.</p>
  
  <p>For each of these tables, I've created a class within my application (so <code>Destinations</code> is a class, <code>Trips</code> is a class, etc.).  I've written a static function for each of these classes that enables objects to be instantiated and their properties assigned from a MySQL query (so each row returned from a <code>SELECT *</code> query results in an object being instantiated and properties assigned).</p>
  
  <p>I'm trying to create a page where my user can view details of all of the trips they have planned.  This page will show the destination (from <code>Destinations</code>), trip details (such as date from <code>Trips</code>) and details of the users they have invited (such as username from <code>Users</code>) and put all of this data in an html table where each trip is a row.</p>
  
  <p>To achieve this, so far I've been instantiating <code>Trips</code> which relate to the user's <code>user_id</code>, <code>Destinations</code> and <code>Invites</code> which relate to those <code>Trips</code>, and <code>Users</code> which relate to those <code>Invites</code>. I've then used nested foreach loops to display these as necessary, such as the below:</p>
  
  <pre><code>foreach($trips as $trip) {
   foreach($invites as $invite) {
     foreach($invited_users as $invited_user) {
        if($invite-&gt;trip_id == $trip-&gt;id &amp;&amp; $invite-&gt;guest_id == $invited_user-&gt;id) {
          echo $invited_user-&gt;name;
                    } } } }
  </code></pre>
  
  <p>Which I can see is horrible and no way to do this.</p>
  
  <p>From reading around, I think I want to use MySQL to join the 4 tables, and then select only data relating to my relevant trips.  What I'm not sure of though is:</p>
  
  <p>a) How do I instantiate the objects and assign their properties correctly from this MySQL result?</p>
  
  <p>b) Even with that done, how do I avoid the expensive <code>foreach</code> loops to display the correct data alongside the correct trip?</p>
  
  <p>Is there a "best practice" way of displaying data from multiple related database tables in an object oriented way?</p>