本文實例講述了ThinkPHP5&5.1框架關聯模型分頁操作。分享給大家供大家參考,具體如下:
利用數據庫的分頁通常比較簡單,但在實際項目中,我們往往需要處理復雜的數據,例如多表操作,這時候我們就需要利用模型層的關聯操作得到最終想要的數據,而這些數據我們其實也是可以利用ThinkPHP5&5.1內置的分頁引擎進行分頁的。
賣的車輛我們稱之為車源,車源和車主之間是多對一關系(車主可以有多輛車,一輛車只屬于一個車主);車源和車輛圖片之間是一對多關系(一輛車有多個圖片,一個圖片只屬于一輛車);車輛還有自定義屬性,它們之間是多對多關系,車輛的級別在車源表是個數字,具體名稱需要到級別表獲取。。。。可以看出,這塊是非常復雜的,完全使用數據庫操作會非常復雜,所以我們選擇使用模型層進行處理。
首先建立模型之間的關系:
1
2
3
4
5
6
7
8
9
10
11
12
|
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' ); } |
同時對應的模型也要建立對應的方法。
在控制器層寫方法:
1
2
3
4
5
6
7
8
|
public function lst() { $cars_model = model( "Cars" ); $cars_list = $cars_model ->getCarsList(); $this ->assign( "cars_list" , $cars_list ); // dump($cars_list); return view(); } |
其中getCarsList()方法在模型層中實現:
1
2
3
4
5
6
7
8
9
10
11
|
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 ; } |
模板上寫法同普通分頁:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
< div class = "ibox-content" > < table class = "table table-bordered" > < thead > < tr > < th >ID</ th > < th >名稱</ th > < th >車主</ th > < th >狀態</ 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程序設計有所幫助。
原文鏈接:https://blog.csdn.net/pan_yuyuan/article/details/81948020