GridView 两表联查/搜索/分页

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

Ⅰ.控制器层Controller

<?php 
namespace backendcontrollers;
header("Content-type:text/html;charset=utf-8");
use Yii;
use yiiwebController; //超级控制器类
use backendmodelsBooksInfo; //表Model类
use backendmodelsInfoSearch; //引入搜索Model类
use yiidataActiveDataProvider; //小部件数据源类
use yiigridGridView; //查询小部件
/**
 *@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 backendmodels;
use Yii;
use yiidbActiveRecord;
/**
 *@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 backendmodels; //命名空间
use Yii;
use yiiaseModel; //引入基类Model
use yiidataActiveDataProvider;  //引入数据源类
/**
 *@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 yiigridGridView;
use yiidataActiveDataProvider;
use yiigridActionColumn;
use yiihelpersHtml;
$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" => "yiigridCheckboxColumn"], //复选框列
    ["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" => "yiigridActionColumn","header"=>"操作"], //动作列
 ],
  "pager" => [//自定义分页样式以及显示内容
    "prevPageLabel"=>"上一页",
    "nextPageLabel"=>"下一页",
    "firstPageLabel" => "第一页",
    "lastPageLabel" => "最后一页",
    "options"=>["style"=>"margin-left:200px;","class"=>"pagination"],
    ],
]);
?>

Ⅴ.效果展示

总结

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