From abd4cd370bc68f2bd4b2b750555f70bb6c640372 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Thu, 4 Jun 2015 21:02:13 +0200 Subject: [PATCH] Adding support for leftJoinWith in BelongsToMany --- src/ORM/Association/BelongsToMany.php | 3 ++- tests/TestCase/ORM/QueryTest.php | 32 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/ORM/Association/BelongsToMany.php b/src/ORM/Association/BelongsToMany.php index 8097dcd6813..d057be51733 100644 --- a/src/ORM/Association/BelongsToMany.php +++ b/src/ORM/Association/BelongsToMany.php @@ -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); } diff --git a/tests/TestCase/ORM/QueryTest.php b/tests/TestCase/ORM/QueryTest.php index 442ff4f8a19..3354fb1dc5c 100644 --- a/tests/TestCase/ORM/QueryTest.php +++ b/tests/TestCase/ORM/QueryTest.php @@ -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())); + } }