Commit bcf5b464 by Qiang Xue

Fixes #2687: ActiveQuery::joinWith() has problem when the query is used twice.

parent 252f49b9
...@@ -236,10 +236,6 @@ class ActiveQuery extends Query implements ActiveQueryInterface ...@@ -236,10 +236,6 @@ class ActiveQuery extends Query implements ActiveQueryInterface
*/ */
protected function createCommandInternal($db) protected function createCommandInternal($db)
{ {
if (!empty($this->joinWith)) {
$this->buildJoinWith();
}
/** @var ActiveRecord $modelClass */ /** @var ActiveRecord $modelClass */
$modelClass = $this->modelClass; $modelClass = $this->modelClass;
if ($db === null) { if ($db === null) {
...@@ -247,6 +243,10 @@ class ActiveQuery extends Query implements ActiveQueryInterface ...@@ -247,6 +243,10 @@ class ActiveQuery extends Query implements ActiveQueryInterface
} }
if ($this->sql === null) { if ($this->sql === null) {
if (!empty($this->joinWith)) {
$this->buildJoinWith();
$this->joinWith = null; // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
}
list ($sql, $params) = $db->getQueryBuilder()->build($this); list ($sql, $params) = $db->getQueryBuilder()->build($this);
} else { } else {
$sql = $this->sql; $sql = $this->sql;
......
...@@ -393,6 +393,13 @@ class ActiveRecordTest extends DatabaseTestCase ...@@ -393,6 +393,13 @@ class ActiveRecordTest extends DatabaseTestCase
$this->assertEquals(2, count($orders[0]->books2)); $this->assertEquals(2, count($orders[0]->books2));
$this->assertEquals(0, count($orders[1]->books2)); $this->assertEquals(0, count($orders[1]->books2));
$this->assertEquals(1, count($orders[2]->books2)); $this->assertEquals(1, count($orders[2]->books2));
// join with count and query
$query = Order::find()->joinWith('customer');
$count = $query->count();
$this->assertEquals(3, $count);
$orders = $query->all();
$this->assertEquals(3, count($orders));
} }
public function testJoinWithAndScope() public function testJoinWithAndScope()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment