1.model中models/article.php
1 <?php
2
3 namespace app\models;
4
5 use Yii;
6
7 /**
8 * This is the model class for table "yii2_article".
9 *
10 * @property string $id
11 * @property integer $category_id
12 * @property string $title
13 * @property string $image
14 * @property string $content
15 * @property string $create_at
16 * @property string $updata_at
17 */
18 class Article extends \yii\db\ActiveRecord
19 {
20 /**
21 * @inheritdoc
22 */
23 public static function tableName()
24 {
25 return 'yii2_article';
26 }
27
28 /**
29 * @inheritdoc
30 */
31 public function rules()
32 {
33 return [
34 [['category_id'], 'integer'],
35 [['desc','content'], 'string'],
36 [['create_at', 'updata_at'], 'safe'],
37 [['title'], 'string', 'max' => 50],
38 [['image'], 'string', 'max' => 100]
39 ];
40 }
41
42 /**
43 * @inheritdoc
44 */
45 public function attributeLabels()
46 {
47 return [
48 'id' => 'ID',
49 'category_id' => '栏目',
50 'title' => '标题',
51 'desc' => '描述',
52 'image' => '封面图片',
53 'content' => '内容',
54 'create_at' => '创建日期',
55 'updata_at' => '修改日期',
56 ];
57 }
58
59 //根据文章查询栏目的信息,hasOne()因为一个文章只属于一个栏目,一比一的方法
60 public function getArticleCategory(){
61 return $this->hasOne(ArticleCategory::className(),['id'=>'category_id']);
62 }
63 }
2.控制器中ArticleController.php
<?php namespace app\controllers; use Yii;
use app\models\Article;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\data\Pagination;
class ArticleController extends Controller
{ //public $layout="main";
public function actionIndex()
{
$article = Article::find();
$articleCount = clone $article; $pageSize = 5; $pages =new Pagination([
'totalCount'=>$articleCount->count(),
'pageSize'=>$pageSize
]) ; $models = $article->offset($pages->offset)
->limit($pages->limit)
->orderBy('id DESC')
->all(); return $this->render('index',[
'models'=>$models,
'pages'=>$pages
]);
}
}
3.视图中view/article/index.php
<?php
/**
* Created by PhpStorm.
* User: moka同学
* Date: 2016/07/22
* Time: 11:13
*/
use yii\widgets\LinkPager;
use \yii\helpers\Url;
?>
<?php
foreach ($models as $model) {
?>
<div class="artcicle-list">
<h4 class="text-left h4">
<a href="<?=Url::toRoute(['article/view','id'=>$model->id]);?>" class="not-set"><?= $model->title ?></a>
</h4> <p class="text-right">
<small><?= $model->create_at ?></small>
</p>
<div class="col-l">
<?= isset($model->image) ? "<div class='face-image'><img src='$model->image' style='width: 120px;height: 120px;margin-right: 10px;vertical-align: text-top '></div>" : ""; ?>
<div class="article-content fl"><?=mb_substr($model->content,0,400,'utf-8').'……' ?><a href="<?=Url::toRoute(['article/view','id'=>$model->id]);?>">查看详情</a></div>
</div>
</div>
<?php } ?>
<div class="pagination-sm text-center">
<?= LinkPager::widget([
'pagination' => $pages,
'options' => [
'class' => 'pagination',
]
]) ?>
</div>
这个是很基础的model使用,如有不对,请联系我。QQ1727728211