Skip to content

Handle case of array of ObjectIDs correctly #1768

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 7 commits into from
Closed
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ composer.lock
*.project
.idea/
.phpunit.result.cache
.vscode
4 changes: 4 additions & 0 deletions src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,10 @@ protected function performUpdate($query, array $options = [])
*/
public function convertKey($id)
{
if (is_array($id)) {
return array_map(array($this, __FUNCTION__), $id);
}

if (is_string($id) && strlen($id) === 24 && ctype_xdigit($id)) {
return new ObjectID($id);
}
Expand Down
19 changes: 14 additions & 5 deletions src/Jenssegers/Mongodb/Relations/BelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,21 @@ public function getHasCompareKey()
*/
public function addConstraints()
{
if (static::$constraints) {
// 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->getOwnerKey(), '=', $this->parent->{$this->foreignKey});
if (!static::$constraints) {
return;
}
// 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.
$foreign = $this->parent->{$this->foreignKey};
// Check if the foreign key is an array, so we can infer the cardinality of the relationship.
if (is_array($foreign)) {
// This means that it is a one-to-many relationship. Try a match using whereIn.
$this->query->whereIn($this->getOwnerKey(), $foreign);
return;
}
// It's a one-to-one relationship, just match using the classic equals operator.
$this->query->where($this->getOwnerKey(), '=', $foreign);
}

/**
Expand Down