2014-12-22 00:39:24 +02:00
|
|
|
<?php
|
|
|
|
/**
|
2014-12-26 05:17:35 +02:00
|
|
|
* @link https://github.com/creocoder/yii2-nested-sets-behavior
|
2015-01-01 08:08:05 +02:00
|
|
|
* @copyright Copyright (c) 2015 Alexander Kochetov
|
2014-12-22 00:39:24 +02:00
|
|
|
* @license http://opensource.org/licenses/BSD-3-Clause
|
|
|
|
*/
|
|
|
|
|
2014-12-26 05:17:35 +02:00
|
|
|
namespace creocoder\nestedsets;
|
2014-12-22 00:39:24 +02:00
|
|
|
|
|
|
|
use yii\base\Behavior;
|
2015-01-03 14:40:03 +02:00
|
|
|
use yii\db\Expression;
|
2014-12-22 00:39:24 +02:00
|
|
|
|
|
|
|
/**
|
2014-12-26 05:17:35 +02:00
|
|
|
* NestedSetsQueryBehavior
|
2014-12-22 00:39:24 +02:00
|
|
|
*
|
2014-12-26 05:18:44 +02:00
|
|
|
* @property \yii\db\ActiveQuery $owner
|
|
|
|
*
|
2014-12-22 00:39:24 +02:00
|
|
|
* @author Alexander Kochetov <creocoder@gmail.com>
|
|
|
|
*/
|
2014-12-26 05:17:35 +02:00
|
|
|
class NestedSetsQueryBehavior extends Behavior
|
2014-12-22 00:39:24 +02:00
|
|
|
{
|
|
|
|
/**
|
2015-01-01 08:08:05 +02:00
|
|
|
* Gets the root nodes.
|
|
|
|
* @return \yii\db\ActiveQuery the owner
|
2014-12-22 00:39:24 +02:00
|
|
|
*/
|
|
|
|
public function roots()
|
|
|
|
{
|
2015-01-03 14:40:03 +02:00
|
|
|
$this->owner->andWhere([(new $this->owner->modelClass())->leftAttribute => 1]);
|
|
|
|
|
|
|
|
return $this->owner;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the leaf nodes.
|
|
|
|
* @return \yii\db\ActiveQuery the owner
|
|
|
|
*/
|
|
|
|
public function leaf()
|
|
|
|
{
|
|
|
|
$model = new $this->owner->modelClass();
|
|
|
|
$db = $model->getDb();
|
|
|
|
|
|
|
|
$this->owner->andWhere(new Expression(
|
|
|
|
$db->quoteColumnName($model->rightAttribute) . ' - ' . $db->quoteColumnName($model->leftAttribute) . ' = 1'
|
|
|
|
));
|
2014-12-22 00:39:24 +02:00
|
|
|
|
|
|
|
return $this->owner;
|
|
|
|
}
|
|
|
|
}
|