可能这个对你有帮助......:)
我正在为类别复制 yii2 的控制器类
<?php
namespace api\modules\v1\controllers;
use Yii;
use yii\rest\Controller;
use api\modules\v1\models\MySearializer;
use api\modules\v1\models\search\CategorySearch;
use api\modules\v1\models\Category;
class CategoryController extends Controller
{
public function actionIndex()
{
$searchModel = new CategorySearch();
$status = false;
$message = '';
$data = (object)[];
$dataProvider = $searchModel->search(Yii::$app->request->getBodyParams());
$obj = new MySearializer();
$obj->collectionEnvelope ='pager';
$ser = $obj->serialize($dataProvider);
return ['status' => true, 'message' => 'Category Listing',
'data' => $ser];
}
public function actionView($id)
{
$status = false;
$message = '';
$data = (object)[];
$model = Category::findOne($id);
if($model)
{
return ['status' => true, 'message' => 'Category View',
'data' => $model];
}else
{
return ['status' => false, 'message' => 'Category not found',
'data' => $data];
}
}
public function actionAllParent()
{
$status = false;
$message = '';
$data = (object)[];
$model = Category::find()->where(['parent'=>0])->all();
if($model)
{
return ['status' => true, 'message' => 'All Parent Category Listing',
'data' => $model];
}else
{
return ['status' => false, 'message' => 'Parent Category not found',
'data' => $data];
}
}
public function actionTree()
{
$status = false;
$message = '';
$data = (object)[];
$model = Category::find()->asArray()->all();
$cattree = $this->CreateTree($model);
print_r($cattree); die;
if($model)
{
return ['status' => true, 'message' => 'All Child Category Listing',
'data' => $model];
}else
{
return ['status' => false, 'message' => 'Child Category not found',
'data' => $data];
}
}
public function actionChild($id)
{
$status = false;
$message = '';
$data = (object)[];
$model = Category::find()->where(['parent'=>$id])->all();
if($model)
{
return ['status' => true, 'message' => 'All Child Category Listing',
'data' => $model];
}else
{
return ['status' => false, 'message' => 'Child Category not found',
'data' => $data];
}
}
public function CreateTree($tree,$parentId=0)
{
$branch =[] ;
foreach ($tree as $element)
{
if ($element['parent'] == $parentId)
{
$children = $this->CreateTree($tree, $element['slno']);
if ($children)
{
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
}