-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathNestedSetsQueryBehavior.php
More file actions
63 lines (52 loc) · 1.6 KB
/
NestedSetsQueryBehavior.php
File metadata and controls
63 lines (52 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
/**
* @link https://github.com/creocoder/yii2-nested-sets
* @copyright Copyright (c) 2015 Alexander Kochetov
* @license http://opensource.org/licenses/BSD-3-Clause
*/
namespace creocoder\nestedsets;
use yii\base\Behavior;
use yii\db\Expression;
/**
* NestedSetsQueryBehavior
*
* @property \yii\db\ActiveQuery $owner
*
* @author Alexander Kochetov <creocoder@gmail.com>
*/
class NestedSetsQueryBehavior extends Behavior
{
/**
* Gets the root nodes.
* @param mixed $id the optional tree id. Default is `null` to query for all root nodes.
* @return \yii\db\ActiveQuery the owner
*/
public function roots($id = null)
{
$model = new $this->owner->modelClass();
$this->owner
->andWhere([$model->leftAttribute => 1])
->addOrderBy([$model->primaryKey()[0] => SORT_ASC]);
if ($id!==null && $model->treeAttribute!==false) {
$this->owner->andWhere([$model->treeAttribute => $id]);
}
return $this->owner;
}
/**
* Gets the leaf nodes.
* @return \yii\db\ActiveQuery the owner
*/
public function leaves()
{
$model = new $this->owner->modelClass();
$db = $model->getDb();
$columns = [$model->leftAttribute => SORT_ASC];
if ($model->treeAttribute !== false) {
$columns = [$model->treeAttribute => SORT_ASC] + $columns;
}
$this->owner
->andWhere([$model->rightAttribute => new Expression($db->quoteColumnName($model->leftAttribute) . '+ 1')])
->addOrderBy($columns);
return $this->owner;
}
}