PHP code example of yii2tech / ar-position
1. Go to this page and download the library: Download yii2tech/ar-position library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yii2tech / ar-position example snippets
use yii\db\ActiveRecord;
use yii2tech\ar\position\PositionBehavior;
class Item extends ActiveRecord
{
public function behaviors()
{
return [
'positionBehavior' => [
'class' => PositionBehavior::className(),
'positionAttribute' => 'position',
],
];
}
}
$records = Item::find()->orderBy(['position' => SORT_ASC])->all();
foreach ($records as $record) {
echo $record->position . ', ';
}
// outputs: 1, 2, 3, 4, 5,...
echo Item::find()->count(); // outputs: 4
$item = new Item();
$item->save();
echo $item->position; // outputs: 5
echo Item::find()->count(); // outputs: 4
$item = new Item();
$item->position = 2; // enforce position '2'
$item->save();
echo $item->position; // outputs: 2 !!!
$item = Item::find()->andWhere(['position' => 3])->one();
$item->position = 5; // switch position to '5'
$item->save();
use yii\db\ActiveRecord;
use yii2tech\ar\position\PositionBehavior;
class FaqQuestion extends ActiveRecord
{
public function behaviors()
{
return [
'positionBehavior' => [
'class' => PositionBehavior::className(),
'positionAttribute' => 'position',
'groupAttributes' => [
'categoryId' // multiple lists varying by 'categoryId'
],
],
];
}
}
echo FaqQuestion::find()->andWhere(['categoryId' => 1])->count(); // outputs: '4'
echo FaqQuestion::find()->andWhere(['categoryId' => 2])->count(); // outputs: '7'
$record = new FaqQuestion();
$record->categoryId = 1;
$record->save();
echo $record->position; // outputs: '5'
$record = new FaqQuestion();
$record->categoryId = 2;
$record->save();
echo $record->position; // outputs: '8'
echo Item::find()->count(); // outputs: 10
$firstItem = Item::find()->andWhere(['position' => 1])->one();
echo $firstItem->getIsFirst(); // outputs: true
echo $firstItem->getIsLast(); // outputs: false
$lastItem = Item::find()->andWhere(['position' => 10])->one();
echo $lastItem->getIsFirst(); // outputs: false
echo $lastItem->getIsLast(); // outputs: true
$item = Item::find()->andWhere(['position' => 5])->one();
$nextItem = $item->findNext();
echo $nextItem->position; // outputs: 6
$prevItem = $item->findPrev();
echo $prevItem->position; // outputs: 4
echo Item::find()->count(); // outputs: 10
$item = Item::find()->andWhere(['position' => 5])->one();
$firstItem = $item->findFirst();
echo $firstItem->position; // outputs: 1
$lastItem = $item->findLast();
echo $lastItem->position; // outputs: 10