Skip to content

Commit

Permalink
Add support to make relation for ObjectID with hasMany and hasOne m…
Browse files Browse the repository at this point in the history
  • Loading branch information
kargnas committed Nov 14, 2017
1 parent dfaa7dd commit f1e36e7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public function match(array $models, Collection $results, $relation)
{
foreach ($models as $model) {
$results = $model->$relation()->getResults();
dd($results);

$model->setParentRelation($this);

Expand Down
45 changes: 45 additions & 0 deletions src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* @package Jenssegers\Mongodb\Relations
*
* @property \Illuminate\Database\Eloquent\Builder $query
* @property string $localKey
*/
trait HasOneOrManyTrait
{
Expand All @@ -32,4 +33,48 @@ public function addConstraints()
$this->query->whereNotNull($this->foreignKey);
}
}

/**
* @inheritdoc
*/
public function addEagerConstraints(array $models)
{
// We'll grab the primary key name of the related models since it could be set to
// a non-standard name and not "id". We will then construct the constraint for
// our eagerly loading query so it returns the proper models from execution.
$key = $this->foreignKey;

$this->query->whereIn($key, $this->getEagerModelKeys($models));
}

/**
* Gather the keys from an array of related models.
*
* @param array $models
* @return array
*/
protected function getEagerModelKeys(array $models)
{
$keys = [];

// First we need to gather all of the keys from the parent models so we know what
// to query for via the eager loading query. We will add them to an array then
// execute a "where in" statement to gather up all of those related records.
foreach ($models as $model) {
if (! is_null($value = $model->{$this->localKey})) {
$keys[] = new ObjectID($value);
}
}

// If there are no keys that were not null we will just return an array with null
// so this query wont fail plus returns zero results, which should be what the
// developer expects to happen in this situation. Otherwise we'll sort them.
if (count($keys) === 0) {
return [null];
}

sort($keys);

return array_values(array_unique($keys));
}
}

0 comments on commit f1e36e7

Please sign in to comment.