Skip to content

Mongodb support for non-existent field #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/Jenssegers/Mongodb/Relations/BelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,25 @@ 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);
}
}

Expand Down