Skip to content

Commit

Permalink
Add alias when using lookup on an inverse relationship
Browse files Browse the repository at this point in the history
  • Loading branch information
josemiguelq authored Mar 31, 2020
1 parent 14da812 commit 1c6fade
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Lookup.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ private function fromReference($fieldName)

$this
->localField('_id')
->foreignField($referencedFieldName);
->foreignField($referencedFieldName)
->alias($fieldName);
}

return $this;
Expand Down
47 changes: 47 additions & 0 deletions tests/Doctrine/ODM/MongoDB/Tests/Aggregation/Stage/LookupTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -420,4 +420,51 @@ private function insertTestData()
$this->dm->persist($referenceUser);
$this->dm->flush();
}

public function testLookupStageAndDefaultAlias()
{
$builder = $this->dm->createAggregationBuilder(\Documents\User::class);
$builder
->lookup('simpleReferenceOneInverse');

$expectedPipeline = [
[
'$lookup' => [
'from' => 'SimpleReferenceUser',
'localField' => '_id',
'foreignField' => 'userId',
'as' => 'simpleReferenceOneInverse',
],
],
];

$this->assertEquals($expectedPipeline, $builder->getPipeline());

$result = $builder->execute()->toArray();
$this->assertCount(1, $result[0]['simpleReferenceOneInverse']);
}

public function testLookupStageAndDefaultAliasOverride()
{
$builder = $this->dm->createAggregationBuilder(\Documents\User::class);
$builder
->lookup('simpleReferenceOneInverse')
->alias('override');

$expectedPipeline = [
[
'$lookup' => [
'from' => 'SimpleReferenceUser',
'localField' => '_id',
'foreignField' => 'userId',
'as' => 'override',
],
],
];

$this->assertEquals($expectedPipeline, $builder->getPipeline());

$result = $builder->execute()->toArray();
$this->assertCount(1, $result[0]['override']);
}
}
2 changes: 1 addition & 1 deletion tests/Documents/SimpleReferenceUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class SimpleReferenceUser
/** @ODM\Id */
public $id;

/** @ODM\ReferenceOne(targetDocument="Documents\User", simple=true, name="userId") @ODM\Index */
/** @ODM\ReferenceOne(targetDocument="Documents\User", simple=true, name="userId", inversedBy="simpleReferenceManyInverse") @ODM\Index */
public $user;

/** @ODM\ReferenceMany(targetDocument="Documents\User", simple=true) */
Expand Down

0 comments on commit 1c6fade

Please sign in to comment.