From 3f3b22529c05b8cbecd692ebc286b1319c8de6a3 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Wed, 28 May 2014 13:04:25 -0500
Subject: [PATCH] orm: Implement proper NULLing of relationships

---
 include/class.orm.php  | 22 +++++++++++++++-------
 include/class.user.php |  7 +------
 2 files changed, 16 insertions(+), 13 deletions(-)

diff --git a/include/class.orm.php b/include/class.orm.php
index b403617b2..b4f65e551 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -73,15 +73,23 @@ class VerySimpleModel {
                 $this->ht[$field] = $value;
                 return;
             }
-            // XXX: Ensure $value instanceof $j['fkey'][0]
-            if ($value->__new__)
-                $value->save();
-            // Capture the object under the object's field name
-            $this->ht[$field] = $value;
+            if ($value === null) {
+                // Pass. Set local field to NULL in logic below
+            }
+            elseif ($value instanceof $j['fkey'][0]) {
+                if ($value->__new__)
+                    $value->save();
+                // Capture the object under the object's field name
+                $this->ht[$field] = $value;
+                $value = $value->get($j['fkey'][1]);
+                // Fall through to the standard logic below
+            }
+            else
+                throw new InvalidArgumentException(
+                    'Expecting NULL or instance of ' . $j['fkey'][0]);
+
             // Capture the foreign key id value
             $field = $j['local'];
-            $value = $value->get($j['fkey'][1]);
-            // Fall through to the standard logic below
         }
         // XXX: Fully support or die if updating pk
         // XXX: The contents of $this->dirty should be the value after the
diff --git a/include/class.user.php b/include/class.user.php
index f736501fc..c169c48cc 100644
--- a/include/class.user.php
+++ b/include/class.user.php
@@ -111,12 +111,7 @@ class UserModel extends VerySimpleModel {
 
     function setOrganization($org, $save=true) {
 
-        if (is_null($org))
-            $this->set('org_id', 0);
-        elseif ($org instanceof Organization)
-            $this->set('org', $org);
-        else // noop
-            return false;
+        $this->set('org', $org);
 
         if ($save)
             $this->save();
-- 
GitLab