yii2实现数据分页
利用yii里面的yiidataPagination类分页
gii生成模型News;手动增加自定义需求函数
namespace appmodels;
use yiidbActiveRecord;
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"]);
}
}
namespace appcontrollers;
use Yii;
use yiiwebController;
<strong>use yiidataPagination;</strong>
use appModelsNews;
use appModelscate;
use appmodelsNewForm;
use yiiwebNotFoundHttpException;
use yiiwebResponse;
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 yiiwebErrorAction;
}
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;
}
}声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: thinkphp中模板的if语句多重判断
- 下一篇: mysql 内存不足引发的坑
