本文實例講述了ThinkPHP5&5.1框架關聯(lián)模型分頁操作。分享給大家供大家參考,具體如下:
利用數(shù)據(jù)庫的分頁通常比較簡單,但在實際項目中,我們往往需要處理復雜的數(shù)據(jù),例如多表操作,這時候我們就需要利用模型層的關聯(lián)操作得到最終想要的數(shù)據(jù),而這些數(shù)據(jù)我們其實也是可以利用ThinkPHP5&5.1內(nèi)置的分頁引擎進行分頁的。
賣的車輛我們稱之為車源,車源和車主之間是多對一關系(車主可以有多輛車,一輛車只屬于一個車主);車源和車輛圖片之間是一對多關系(一輛車有多個圖片,一個圖片只屬于一輛車);車輛還有自定義屬性,它們之間是多對多關系,車輛的級別在車源表是個數(shù)字,具體名稱需要到級別表獲取。。。??梢钥闯?,這塊是非常復雜的,完全使用數(shù)據(jù)庫操作會非常復雜,所以我們選擇使用模型層進行處理。
首先建立模型之間的關系:
public function selfattribute(){ return $this->belongsToMany("Selfattribute",'cars_selfattribute','selfattribute_id','cars_id');}public function carsimg(){ return $this->hasMany('Carsimg');}public function member(){ return $this->belongsTo('/app/index/model/Member');}
同時對應的模型也要建立對應的方法。
在控制器層寫方法:
public function lst(){ $cars_model = model("Cars"); $cars_list = $cars_model->getCarsList(); $this->assign("cars_list",$cars_list); // dump($cars_list); return view();}
其中getCarsList()方法在模型層中實現(xiàn):
public function getCarsList() { $cars_list = Cars::paginate(2)->each(function($value,$key){ $level_find = db("level")->where('id',$value['level'])->value('name'); $value['level_name'] = $level_find; $value->carsimg; $value->member; $value->selfattribute; }); return $cars_list; }
模板上寫法同普通分頁:
<div class="ibox-content"> <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>名稱</th> <th>車主</th> <th>狀態(tài)</th> <th>操作</th> </tr> </thead> <tbody> {volist name="cars_list" id="vo"} <tr> <td>{$vo.id}</td> <td><a href="{:url('index/cars/carsdetails',array('id'=>$vo.id))}" rel="external nofollow" >{$vo.full_name}</a></td> <td>{$vo.member.member_name}</td> <td> {switch $vo.status} {case 1}上架{/case} {case 0}下架{/case} {case -1}已售{/case} {default /}未審核 {/switch} </td> <td> <div class="btn-group open"> <button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" aria-expanded="true">操作 <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="">修改</a> </li> <li><a href="">刪除</a> </li> </ul> </div> </td> </tr> {/volist} </tbody> </table> {$cars_list|raw}</div>
希望本文所述對大家基于ThinkPHP框架的PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選