From ea07a9ff9718f8b126fbd61e40de41ba104363a9 Mon Sep 17 00:00:00 2001 From: foxbit19 Date: Thu, 16 Apr 2015 16:30:20 +0200 Subject: [PATCH 1/2] Mongodb support for non-existent field Mongodb has no fixed structure for collections. So a field may be non-existent in mongodb. In this case, the property that represents the foreignKey cannot be retrieved and an ErrorException will be thrown. I've added a try-catch construct to avoid the case in which the field doesn't exists. --- src/Jenssegers/Mongodb/Relations/BelongsTo.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsTo.php b/src/Jenssegers/Mongodb/Relations/BelongsTo.php index dd5de1f24..fbd0f3dea 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsTo.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsTo.php @@ -11,10 +11,24 @@ public function addConstraints() { if (static::$constraints) { + // The foreign key field may be non-existent in mongodb. + // In this case, the property $this->parent->{$this->foreignKey} cannot be retrieved + // and an ErrorException will be thrown. + // The following try-catch construct avoids the case in which the field doesn't exists. + try + { + $foreign_key = $this->parent->{$this->foreignKey}; + } + catch (ErrorException $ex) + { + // The property doesn't exists. Set it to null + $foreign_key = null; + } + // For belongs to relationships, which are essentially the inverse of has one // or has many relationships, we need to actually query on the primary key // of the related models matching on the foreign key that's on a parent. - $this->query->where($this->otherKey, '=', $this->parent->{$this->foreignKey}); + $this->query->where($this->otherKey, '=', $foreign_key); } } From f3e5c7f5dde76bf578c41ba9f4c3edaeefc4cff2 Mon Sep 17 00:00:00 2001 From: foxbit19 Date: Thu, 16 Apr 2015 16:33:59 +0200 Subject: [PATCH 2/2] Fix tabs --- src/Jenssegers/Mongodb/Relations/BelongsTo.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsTo.php b/src/Jenssegers/Mongodb/Relations/BelongsTo.php index fbd0f3dea..ed93c90e5 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsTo.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsTo.php @@ -21,7 +21,8 @@ public function addConstraints() } catch (ErrorException $ex) { - // The property doesn't exists. Set it to null + // The property doesn't exists. + // Set it to null $foreign_key = null; }