Navigation Menu

Skip to content

Commit

Permalink
Fix IN replacement in virtual fields for MYSQL.
Browse files Browse the repository at this point in the history
  • Loading branch information
euromark committed Oct 30, 2014
1 parent 1e8f12f commit e5b45bc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/Cake/Model/Datasource/DboSource.php
Expand Up @@ -1410,11 +1410,10 @@ public function fetchAssociated(Model $Model, $query, $ids) {
protected function _fetchHasMany(Model $Model, $query, $ids) {
$ids = array_unique($ids);

$query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
if (count($ids) > 1) {
$query = str_replace('= (', 'IN (', $query);
$query = str_replace('= ({$__cakeID__$}', 'IN ({$__cakeID__$}', $query);
}

$query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
return $this->fetchAll($query, $Model->cacheQueries);
}

Expand Down
25 changes: 25 additions & 0 deletions lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php
Expand Up @@ -3427,6 +3427,31 @@ public function testVirtualFields() {
$this->assertEquals($expected, $result);
}

/**
* test find() generating usable virtual fields to use in query
*
* @return void
*/
public function testVirtualFieldsWithSubquery() {
$this->loadFixtures('Article', 'Comment', 'User', 'Tag', 'ArticlesTag');
$this->Dbo->virtualFieldSeparator = '__';
$Article = ClassRegistry::init('Article');
$commentsTable = $this->Dbo->fullTableName('comments', false, false);
$Article->Comment->virtualFields = array(
'extra' => 'SELECT id FROM ' . $commentsTable . ' WHERE id = (SELECT 1)',
);
$conditions = array('Article.id' => array(1, 2));
$contain = array('Comment.extra');
$result = $Article->find('all', compact('conditions', 'contain'));

$expected = 'SELECT `Comment`.`id`, `Comment`.`article_id`, `Comment`.`user_id`, `Comment`.`comment`, `Comment`.`published`, `Comment`.`created`,' .
' `Comment`.`updated`, (SELECT id FROM comments WHERE id = (SELECT 1)) AS `Comment__extra`' .
' FROM `cake_test`.`comments` AS `Comment` WHERE `Comment`.`article_id` IN (1, 2)';
$test = ConnectionManager::getDatasource('test');
$log = $test->getLog();
$this->assertTextEquals($expected, $log['log'][116]['query']);
}

/**
* test conditions to generate query conditions for virtual fields
*
Expand Down

0 comments on commit e5b45bc

Please sign in to comment.