<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\actions;

use Yii;

/**
 * 前台公用的排序动作类
 * 
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */

class Sort extends \yii\base\Action
{
	/**
	 * @var class 当前操作所属模型 
	 */
    public $model; 

 
    public function run()
    {
		$this->model === null && $this->model = $this->controller->model;

		$tableName = call_user_func([$this->model, 'tableName']);
		$pks = call_user_func([$this->model, 'primaryKey']);

		$commond = Yii::$app->db->createCommand();

		$sort = Yii::$app->request->post('sort');

		$session = Yii::$app->getSession();
		if (empty($sort) || empty($pks)) {
			$session->setFlash('error', '要排序的对象不存在');
		}
		else {
			foreach ($sort as $id => $value) {
				$commond->update($tableName ,['sort' => $value], $pks[0].' = :id', [':id' => $id])->execute();
			}
			$session->setFlash('success', '排序成功');
		}
		
		return $this->controller->flash(['url' => [$this->controller->id.'/index']]);

    } 
		
}
