Yii2.0小部件GridView(两表联查/搜索/分页)功能的实现代码

时间:2019-03-31
本文章向大家介绍Yii2.0小部件GridView(两表联查/搜索/分页)功能的实现代码,主要包括Yii2.0小部件GridView(两表联查/搜索/分页)功能的实现代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 GridView 两表联查/搜索/分页

当我们在一个网格视图中显示活动数据的时候,你可能会遇到这种情况,就是显示关联表的列的值,为了使关联列能够排序,你需要连接关系表,以及添加排序规则到数据提供者的排序组件中,对数据进行搜索,排序。

Ⅰ.控制器层Controller

<?php 
namespace backend\controllers;
header("Content-type:text/html;charset=utf-8");
use Yii;
use yii\web\Controller; //超级控制器类
use backend\models\BooksInfo; //表Model类
use backend\models\InfoSearch; //引入搜索Model类
use yii\data\ActiveDataProvider; //小部件数据源类
use yii\grid\GridView; //查询小部件
/**
 *@abstract BooksController
 *@author NING <[email ning@163.com]>
 *@version [version 1.0] [书籍管理]
 */
class BooksInfoController extends Controller
{
 
 //书籍列表
 public function actionIndex()
 {
 $searchModel = new InfoSearch(); //实例化searchModel[搜索Model]
 if(!empty($_GET['InfoSearch'])){
  $getSearch = Yii::$app->request->get(); //接收搜索字段
  $data = $searchModel->search($getSearch);
 }else{
  //小部件查询数据
  $data = new ActiveDataProvider([
    'query' => BooksInfo::find(), //查询数据
    'pagination' => [
      'pageSize' => 2, //每页显示条数
    ],
    'sort' => [
      'defaultOrder' => [
        // 'created_at' => SORT_DESC,
        'id' => SORT_ASC, //[字段]设置排序·
      ]
    ],
  ]);
 }
 //传送查询数据、搜素Model
 return $this->render('index',['data'=>$data,'searchModel'=>$searchModel]);
 }
?>

Ⅱ.查询模型层Model

<?php 
namespace backend\models;
use Yii;
use yii\db\ActiveRecord;
/**
 *@abstract [BookForm]
 *@author NING <[email ning@163.com]>
 *@version [vector 1.0] [书籍详情模型]
 */
class BooksInfo extends ActiveRecord
{
 /**
   * @设置表名
   */
  public static function tableName()
  {
    return '{{%books_info}}';
  }
  //关联表
  public function getBooksType(){
    // hasOne要求返回两个参数 第一个参数是关联表的类名 第二个参数是两张表的关联关系 
    // 这里id是books_type表的id, 关联books_info表的type_id 
    return $this->hasOne(BooksType::className(), ['id' => 'type_id']);
  }
 public function attributeLabels()
 {
 return [
  'id' => 'ID',
  'book_name' => '书籍名称',
  'book_face' => '书籍封面',
  'type_id' => '书籍分类ID',
  'type_name' => '书籍分类',
 ];
 }
}
?>

Ⅲ.搜索模型层Search

<?php
namespace backend\models; //命名空间
use Yii;
use yii\base\Model; //引入基类Model
use yii\data\ActiveDataProvider;  //引入数据源类
/**
 *@abstract [搜索Model]
 *@return [type]
 *@author NING <[email ning@163.com]>
 */
// 注意:此处继承的是查询Model--->BooksInfo
class InfoSearch extends BooksInfo
{
  public $type_name; //定义属性变量
  // 只有在 rules() 函数中声明的字段才可以搜索
  public function rules()
  {
    return [
      // [['book_name','type_name'], 'safe'],
      [['type_name'], 'safe'],
    ];
  }
  public function scenarios()
  {
    // 旁路在父类中实现的 scenarios() 函数
    return Model::scenarios();
  }
  public function search($params)
  {
    $query = BooksInfo::find();
    $dataProvider = new ActiveDataProvider([
      'query' => $query,
      'pagination' => [
        'pageSize' => 1,
      ],
    ]);
    /*这里的articlecategory是article模型里面关联的方法名,除了首字母,其他都要完全一样,否则会报错*/
    $query->joinWith(['booksType']);
    // 从参数的数据中加载过滤条件,并验证
    if (!($this->load($params) && $this->validate())) {
      return $dataProvider;
    }
    // 增加过滤条件来调整查询对象
    $query->andFilterWhere(['like', 'book_name', $this->book_name]);
    //添加关联字段过滤条件[注意:此处books_type.type_name中books_type为分类表名]
    $query->andFilterWhere(['like', 'books_type.type_name', $this->type_name]);
    return $dataProvider;
  }
}
?>

Ⅳ.视图层View

<?php 
use yii\grid\GridView;
use yii\data\ActiveDataProvider;
use yii\grid\ActionColumn;
use yii\helpers\Html;
$this->title = '图书列表';
?>
<!-- 面包屑 -->
<ol class="breadcrumb">
 <li><a href="#" rel="external nofollow" rel="external nofollow" >Home</a></li>
 <li><a href="#" rel="external nofollow" rel="external nofollow" >图书信息</a></li>
 <li class="active">图书列表</li>
</ol>
<?php
echo GridView::widget([
 'dataProvider' => $data,  //数据源
  'filterModel' => $searchModel, //搜索列
 'columns' => [
    // ['filterModel' => $searchModel],
    ['class' => 'yii\grid\CheckboxColumn'], //复选框列
    ['attribute' => 'id'],
   ['attribute' => 'book_name',],
    ['attribute' => 'book_face','content'=>function($model){
     // 图片显示
     return Html::img($model->book_face,['width'=>'50']);
    }],
 [
      'attribute' => 'type_name',
      'value' => 'booksType.type_name', //两表联查[书籍类型]
    ],
    ['class' => 'yii\grid\ActionColumn','header'=>'操作'], //动作列
 ],
  'pager' => [//自定义分页样式以及显示内容
    'prevPageLabel'=>'上一页',
    'nextPageLabel'=>'下一页',
    'firstPageLabel' => '第一页',
    'lastPageLabel' => '最后一页',
    'options'=>['style'=>'margin-left:200px;','class'=>"pagination"],
    ],
]);
?>

Ⅴ.效果展示

总结

以上所述是小编给大家介绍的Yii2.0小部件GridView(两表联查/搜索/分页)功能的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!