title: Database abstraction schema manually without ORM
body: <p>I'm in the following standardsituation: I have two model objects from class ShippingGroup and Shipping where Shipping is a child of ShippingGroup. ShippingGroup->shippings holds the kids as usual. In the mySql database I have the following entities:</p>
  
  <p><a href="https://i.stack.imgur.com/u7mxG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u7mxG.png" alt="Simple case"></a></p>
  
  <p>I deal with those situations now for quite a long time every now and then and always have this doubt to not doing it right when it comes to CRUD. Creat, read, delete is of course easy, but update is not. In my opinion.</p>
  
  <p>I know I could use an <strong>ORM</strong> and did it already but I'm not really satisfied by the solutions out there (tried doctrine and redbeans) and want to do manually to have influence on design and performance.</p>
  
  <p>Would anyone please be so kind an post an example for one-to-many, many-to-one and many-to-many relationships? Or at least hint me a free resource like a blog-post or something.</p>
  
  <p>Thank you!</p>
  
  <p><em>My usual approach:</em></p>
  
  <pre><code>if (!is_object($shipping_group) ||
          get_class($shipping_group) != "ShippingGroup" ||
          $shipping_group-&gt;shipping_group_id === NULL) return;
  
      global $db;
  
      $sql = "UPDATE ShippingGroups SET label={$shipping_group-&gt;label} WHERE shipping_group_id={$shipping_group-&gt;shipping_group_id};";
  
      if ($db-&gt;query($sql)) {
  
          // shippings
  
          $childs_old = array();
          $childs_new = array();
  
          foreach ($shipping_group-&gt;shippings as $shipping) {
  
              if ($shipping-&gt;shipping_id === NULL) {
                  $childs_new[$shipping-&gt;shipping_id] = $shipping;
              } else {
                  $childs_old[$shipping-&gt;shipping_id] = $shipping;
              }
          }
  
  
          $sql = "SELECT shipping_id FROM Shippings WHERE shipping_group_id={$shipping_group-&gt;shipping_group_id};";
  
          if ($db_shippings = $db-&gt;query($sql)) {
  
              while ($row = $db_shippings-&gt;fetch_array(MYSQLI_ASSOC)) {
  
                  $shipping_id = $row['shipping_id'];
  
                  if (isset($childs_old[$shipping_id])) {
                      $this-&gt;update_shipping($childs_new[$shipping_id]);
                  } elseif (isset($childs_new[$shipping_id]) {
                      $this-&gt;create_shipping($childs_new[$shipping_id]);
                  } else {
                      $this-&gt;delete_shipping($childs_new[$shipping_id]);
                      // $db-&gt;query("DELETE FROM Shippings WHERE shipping_id={$shipping_id}");
                  }
  
              }
          }
  
  
      }
  
  
  
  }
  </code></pre>