yii2实现数据分页

利用yii里面的yii\data\Pagination类分页

gii生成模型News;手动增加自定义需求函数

namespace app\models;
use yii\db\ActiveRecord;

class News extends ActiveRecord{
	
	public static function tableName(){
		return '{{%news}}';
	}



    /**
    *@检查标题是否唯一
    */
	public static function ckunique($attribute,$value){
		$model =new News();
		$count=Static::find()->where("$attribute='$value'")->count();
		if($count){
			return true;
		}
	}

	/**
	 * @news与cate关联,获取关联cate信息
	 */

	 public function getCate(){
	 	return $this->hasOne(Cate::className(),["cid"=>"cid"]);
	 }
}


控制器NewsControler

namespace app\controllers;
use Yii;
use yii\web\Controller;
<strong>use yii\data\Pagination;</strong>
use app\Models\News;
use app\Models\cate;
use app\models\NewForm;
use yii\web\NotFoundHttpException;
use yii\web\Response;


class NewsController extends controller{

	
	public function actionIndex(){
		$model = new News();//实例化模型

        
		$arr=$model->find()->asArray()->limit(10)->all();<span style="font-family: Arial, Helvetica, sans-serif;">//将AR查询结果保存为数组</span>
		$count=$model->find()->count();
		$page=new Pagination(['defaultPageSize'=>10,'totalCount'=>$count]);
                $data=$model->find()->orderBy('id')->offset($page->offset)->limit($page->limit)->all();
           return $this->render('index',['page'=>$page,'data'=>$data]);
  
	}



	function actionError(){
		throw new yii\web\ErrorAction;
	}

	function actionShow($id){
		$this->layout='@app/views/layouts/main.php';//定义指定的lauout文件
		$model=new News();
		$data=$model::findOne($id);//另一种方法实现包含cate,$data=News::find()->joinWith('cate')->where(["id"=>$id])->one();
                $cate=$data->cate;//通过hasOne关联,获取cate属性也可以通过$data->getCate()-all()获取;

		return $this->render('show',['cate'=>$data->cate->cate,'data'=>$data]);
		
	}

	function actionForm(){
		$model=new NewForm();
		if($model->load(Yii::$app->request->post()) && $model->validate()){
		   $obj=Yii::$app->request->post('NewForm');

		   $this->p($obj);
		}else{
			return $this->render('form',['model'=>$model]);
		}
		
	}

	function actionCate($id){
		
		$data= Cate::find()->where(['cid' =>$id])->one();

		if(false==$data){
			throw new NotFoundHttpException(404);
			exit(0);
		}

		

		//利用respnse,发送utf-8格式的网页

         /*$headers=Yii::$app->response->headers;
 		 $headers->add("Content-type","text/html;charset=utf-8");
 		 print_r($data->news);*/
 		 

        //利用response,发送json格式数据
		
        $response=Yii::$app->response;
        $response->format=Response::FORMAT_JSON;
        $response->data=$data->news;

	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值