Skip to content

Commit 5ff3b4d

Browse files
committed
Добавлен DataProvider
1 parent 392bdb6 commit 5ff3b4d

File tree

2 files changed

+147
-31
lines changed

2 files changed

+147
-31
lines changed

src/QueryRelationDataProvider.php

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
<?php
2+
3+
4+
namespace Smoren\Yii2\QueryRelationManager;
5+
6+
7+
use yii\data\BaseDataProvider;
8+
use yii\db\Connection;
9+
use yii\db\Query;
10+
11+
class QueryRelationDataProvider extends BaseDataProvider
12+
{
13+
/**
14+
* @var QueryRelationManager
15+
*/
16+
public $queryRelationManager;
17+
18+
/**
19+
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
20+
* If not set, the default DB connection will be used.
21+
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
22+
*/
23+
public $db;
24+
25+
/**
26+
* @var string|callable имя столбца с ключом или callback-функция, возвращающие его
27+
*/
28+
public $key;
29+
30+
/**
31+
* Prepares the data models that will be made available in the current page.
32+
* @return array the available data models
33+
* @throws QueryRelationManagerException
34+
*/
35+
protected function prepareModels()
36+
{
37+
$pagination = $this->getPagination();
38+
39+
if($pagination === false) {
40+
$models = $this->queryRelationManager->all($this->db);
41+
} else {
42+
$limit = $pagination->getLimit();
43+
$offset = $pagination->getOffset();
44+
45+
$pagination->totalCount = $this->getTotalCount();
46+
47+
$pkField = $this->queryRelationManager->getMainTablePkField();
48+
49+
$ids = $this->queryRelationManager
50+
->prepare()
51+
->select($pkField)
52+
->distinct()
53+
->limit($limit)
54+
->offset($offset)
55+
->column();
56+
57+
$models = $this->queryRelationManager->filter(function(Query $q) use ($pkField, $ids) {
58+
$q->andWhere([$pkField => $ids]);
59+
})->all();
60+
}
61+
62+
return $models;
63+
}
64+
65+
/**
66+
* Prepares the keys associated with the currently available data models.
67+
* @param array $models the available data models
68+
* @return array the keys
69+
*/
70+
protected function prepareKeys($models)
71+
{
72+
if($this->key !== null) {
73+
$keys = [];
74+
75+
foreach($models as $model) {
76+
if(is_string($this->key)) {
77+
$keys[] = $model[$this->key];
78+
} else {
79+
$keys[] = call_user_func($this->key, $model);
80+
}
81+
}
82+
83+
return $keys;
84+
} else {
85+
return array_keys($models);
86+
}
87+
}
88+
89+
/**
90+
* Returns a value indicating the total number of data models in this data provider.
91+
* @return int total number of data models in this data provider.
92+
*/
93+
protected function prepareTotalCount()
94+
{
95+
return $this->queryRelationManager
96+
->prepare()
97+
->select($this->queryRelationManager->getMainTablePkField())
98+
->distinct()
99+
->count();
100+
}
101+
}

src/QueryRelationManager.php

Lines changed: 46 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,20 @@ class QueryRelationManager
2020
protected $query;
2121

2222
/**
23-
* @var string псевдоним таблицы, данные из которой хотим получить
23+
* @var string псевдоним основной таблицы запроса
2424
*/
2525
protected $mainTableAlias;
2626

2727
/**
28-
* @var string имя таблицы, данные из которой хотим получить
28+
* @var string имя основной таблицы запроса
2929
*/
3030
protected $mainTableName;
3131

32+
/**
33+
* @var string первичный ключ основной таблицы запроса
34+
*/
35+
protected $mainTablePkField;
36+
3237
/**
3338
* @var callable[] список анонимных функций, которые будут модифицировать запрос
3439
*/
@@ -342,37 +347,11 @@ public function all(?Connection $db = null): array
342347
return array_values($maps[$this->mainTableAlias]);
343348
}
344349

345-
/**
346-
* Возвращает текст SQL-запроса
347-
* @return string текст SQL-запроса
348-
*/
349-
public function getRawSql(): string
350-
{
351-
$this->prepare();
352-
353-
return $this->query->createCommand()->getRawSql();
354-
}
355-
356-
/**
357-
* QueryRelationManager constructor.
358-
* @param string $className имя класса сущности ActiveRecord
359-
* @param string $alias псевдоним таблицы сущности
360-
* @param string $fieldJoinTo имя поля, на которое будут ссылаться подключаемые сущности
361-
* @param string $primaryFieldName имя поля первичного ключа таблицы
362-
* @throws QueryRelationManagerException
363-
*/
364-
protected function __construct(string $className, string $alias, string $fieldJoinTo, string $primaryFieldName = 'id')
365-
{
366-
$this->mainTableAlias = $alias;
367-
$this->mainTableName = $this->getTableName($className);
368-
$this->addAliases($className, $alias, $fieldJoinTo, $primaryFieldName);
369-
}
370-
371350
/**
372351
* Создает и выстраивает SQL-запрос
373-
* @return $this
352+
* @return Query
374353
*/
375-
protected function prepare(): self
354+
public function prepare(): Query
376355
{
377356
$this->query = new Query();
378357

@@ -403,7 +382,43 @@ protected function prepare(): self
403382
$modifier($this->query);
404383
}
405384

406-
return $this;
385+
return $this->query;
386+
}
387+
388+
/**
389+
* Возвращает текст SQL-запроса
390+
* @return string текст SQL-запроса
391+
*/
392+
public function getRawSql(): string
393+
{
394+
$this->prepare();
395+
396+
return $this->query->createCommand()->getRawSql();
397+
}
398+
399+
/**
400+
* Возвращает первичный ключ основной таблицы с префиксом в виде алиаса этой таблицы
401+
* @return string
402+
*/
403+
public function getMainTablePkField(): string
404+
{
405+
return "{$this->mainTableAlias}.{$this->mainTableField}";
406+
}
407+
408+
/**
409+
* QueryRelationManager constructor.
410+
* @param string $className имя класса сущности ActiveRecord
411+
* @param string $alias псевдоним таблицы сущности
412+
* @param string $fieldJoinTo имя поля, на которое будут ссылаться подключаемые сущности
413+
* @param string $primaryFieldName имя поля первичного ключа таблицы
414+
* @throws QueryRelationManagerException
415+
*/
416+
protected function __construct(string $className, string $alias, string $fieldJoinTo, string $primaryFieldName = 'id')
417+
{
418+
$this->mainTableAlias = $alias;
419+
$this->mainTableName = $this->getTableName($className);
420+
$this->mainTableField = $fieldJoinTo;
421+
$this->addAliases($className, $alias, $fieldJoinTo, $primaryFieldName);
407422
}
408423

409424
/**

0 commit comments

Comments
 (0)