本文實(shí)例講述了ThinkPHP5&5.1框架關(guān)聯(lián)模型分頁(yè)操作。分享給大家供大家參考,具體如下:
利用數(shù)據(jù)庫(kù)的分頁(yè)通常比較簡(jiǎn)單,但在實(shí)際項(xiàng)目中,我們往往需要處理復(fù)雜的數(shù)據(jù),例如多表操作,這時(shí)候我們就需要利用模型層的關(guān)聯(lián)操作得到最終想要的數(shù)據(jù),而這些數(shù)據(jù)我們其實(shí)也是可以利用ThinkPHP5&5.1內(nèi)置的分頁(yè)引擎進(jìn)行分頁(yè)的。
賣的車輛我們稱之為車源,車源和車主之間是多對(duì)一關(guān)系(車主可以有多輛車,一輛車只屬于一個(gè)車主);車源和車輛圖片之間是一對(duì)多關(guān)系(一輛車有多個(gè)圖片,一個(gè)圖片只屬于一輛車);車輛還有自定義屬性,它們之間是多對(duì)多關(guān)系,車輛的級(jí)別在車源表是個(gè)數(shù)字,具體名稱需要到級(jí)別表獲取。。。。可以看出,這塊是非常復(fù)雜的,完全使用數(shù)據(jù)庫(kù)操作會(huì)非常復(fù)雜,所以我們選擇使用模型層進(jìn)行處理。
首先建立模型之間的關(guān)系:
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');}
同時(shí)對(duì)應(yīng)的模型也要建立對(duì)應(yīng)的方法。
在控制器層寫方法:
public function lst(){ $cars_model = model("Cars"); $cars_list = $cars_model->getCarsList(); $this->assign("cars_list",$cars_list); // dump($cars_list); return view();}
其中g(shù)etCarsList()方法在模型層中實(shí)現(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; }
模板上寫法同普通分頁(yè):
<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>
希望本文所述對(duì)大家基于ThinkPHP框架的PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選