mirror of
https://github.com/elyby/accounts.git
synced 2024-12-25 22:59:53 +05:30
Расширен функционал Yii2 QueryBuilder: теперь функционал ORDER BY FIELD встроен внутрь билдера
This commit is contained in:
parent
5d1dab6e92
commit
78e5d3e103
@ -12,6 +12,9 @@ return [
|
||||
'username' => getenv('MYSQL_USER'),
|
||||
'password' => getenv('MYSQL_PASSWORD'),
|
||||
'charset' => 'utf8',
|
||||
'schemaMap' => [
|
||||
'mysql' => common\db\mysql\Schema::class,
|
||||
],
|
||||
],
|
||||
'mailer' => [
|
||||
'class' => yii\swiftmailer\Mailer::class,
|
||||
|
39
common/db/mysql/QueryBuilder.php
Normal file
39
common/db/mysql/QueryBuilder.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
12
common/db/mysql/Schema.php
Normal file
12
common/db/mysql/Schema.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
16
tests/codeception/common/unit/db/mysql/QueryBuilderTest.php
Normal file
16
tests/codeception/common/unit/db/mysql/QueryBuilderTest.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user