利用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"]);
}
}
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;
}
}