Skip to content

Commit

Permalink
Adding support for leftJoinWith in BelongsToMany
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jun 4, 2015
1 parent 931dc06 commit abd4cd3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/ORM/Association/BelongsToMany.php
Expand Up @@ -254,10 +254,11 @@ public function attachTo(Query $query, array $options = [])
}

unset($options['queryBuilder']);
$type = array_intersect_key($options, ['joinType' => 1, 'fields' => 1]);
$options = ['conditions' => [$cond]] + compact('includeFields');
$options['foreignKey'] = $this->targetForeignKey();
$assoc = $this->_targetTable->association($junction->alias());
$assoc->attachTo($query, $options);
$assoc->attachTo($query, $options + $type);
$query->eagerLoader()->addToJoinsMap($junction->alias(), $assoc, true);
}

Expand Down
32 changes: 32 additions & 0 deletions tests/TestCase/ORM/QueryTest.php
Expand Up @@ -2707,4 +2707,36 @@ public function testLeftJoinWith()
$this->assertEquals([1, 1, 3], $results->extract('id')->toList());
$this->assertEquals(['id', 'name'], array_keys($results->first()->toArray()));
}

/**
* Tests that leftJoinWith() creates a left join with a given association and
* that no fields from such association are loaded.
*
* @return void
*/
public function testLeftJoinWithNested()
{
$table = TableRegistry::get('authors');
$articles = $table->hasMany('articles');
$articles->belongsToMany('tags');

$results = $table
->find()
->select(['total_articles' => 'count(articles.id)'])
->leftJoinWith('articles.tags', function ($q) {
return $q->where(['tags.name' => 'tag3']);
})
->autoFields(true)
->group(['authors.id']);

$expected = [
1 => 2,
2 => 0,
3 => 1,
4 => 0
];
$this->assertEquals($expected, $results->combine('id', 'total_articles')->toArray());
$fields = ['total_articles', 'id', 'name'];
$this->assertEquals($fields, array_keys($results->first()->toArray()));
}
}

0 comments on commit abd4cd3

Please sign in to comment.