Расширен функционал Yii2 QueryBuilder: теперь функционал ORDER BY FIELD встроен внутрь билдера

This commit is contained in:
ErickSkrauch 2016-09-21 11:12:40 +03:00
parent 5d1dab6e92
commit 78e5d3e103
4 changed files with 70 additions and 0 deletions

View File

@ -12,6 +12,9 @@ return [
'username' => getenv('MYSQL_USER'), 'username' => getenv('MYSQL_USER'),
'password' => getenv('MYSQL_PASSWORD'), 'password' => getenv('MYSQL_PASSWORD'),
'charset' => 'utf8', 'charset' => 'utf8',
'schemaMap' => [
'mysql' => common\db\mysql\Schema::class,
],
], ],
'mailer' => [ 'mailer' => [
'class' => yii\swiftmailer\Mailer::class, 'class' => yii\swiftmailer\Mailer::class,

View File

@ -0,0 +1,39 @@
<?php
namespace common\db\mysql;
use yii\db\Expression;
use yii\db\mysql\QueryBuilder as MysqlQueryBuilder;
class QueryBuilder extends MysqlQueryBuilder {
public function buildOrderBy($columns) {
if (empty($columns)) {
return '';
}
$orders = [];
foreach($columns as $name => $direction) {
if ($direction instanceof Expression) {
$orders[] = $direction->expression;
} elseif (is_array($direction)) {
// This is new feature
if (empty($direction)) {
continue;
}
$fieldValues = [];
foreach($direction as $fieldValue) {
$fieldValues[] = $this->db->quoteValue($fieldValue);
}
$orders[] = 'FIELD(' . $this->db->quoteColumnName($name) . ',' . implode(',', $fieldValues) . ')';
// End of new feature
} else {
$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
}
}
return 'ORDER BY ' . implode(', ', $orders);
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace common\db\mysql;
use yii\db\mysql\Schema as MysqlSchema;
class Schema extends MysqlSchema {
public function createQueryBuilder() {
return new QueryBuilder($this->db);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace codeception\common\unit\db\mysql;
use common\db\mysql\QueryBuilder;
use tests\codeception\common\unit\TestCase;
use Yii;
class QueryBuilderTest extends TestCase {
public function testBuildOrderByField() {
$queryBuilder = new QueryBuilder(Yii::$app->db);
$result = $queryBuilder->buildOrderBy(['dummy' => ['first', 'second']]);
$this->assertEquals("ORDER BY FIELD(`dummy`,'first','second')", $result);
}
}