<span style="font-size:14px;">ThinkPHP的多表查询+分页范例 对于一个PHP程序员来说,多表查询是经常遇到的事,下面介绍一下ThinkPHP的多表查询+分页范例 <?php $db = M( "Article" ); $fix = C( "DB_PREFIX" ); $table = $fix."article"; $table2 = $fix."article_category"; $page_size = 15; //每页显示记录数 $record_sum = count( $db -> field('art_id') -> where( "art_public='1'" ) -> select() );//记录总数 $Page = new ZYPage($record_sum, $page_size, 5); $list = $db -> field( "$table.art_id,$table.art_title,$table.art_content,$table.art_description,$table2.cate_id,$table2.cate_name" ) -> join( "$table2 on $table.cate_id=$table2.cate_id" ) -> where( "$table.art_public='1'" ) -> order( "$table.art_create_time desc,$table.art_id desc" ) -> limit($Page->firstRow.",".$Page->listRows) -> select(); $this -> assign( "article", $list); //输出文章列表 $show = $Page -> show(); $this -> assign( "page", $show); //输出分页 ?> </span>
例2:(自己写的)
//显示某一用户,某一订单详情(order详情、fllow_order详情 public function viewOneOrder(){ import('ORG.Util.Page'); $userid = $_POST['userid']; $orderid = $_POST['orderid']; if(empty($userid)){ $result=array('err_no' =>1001,'err_msg'=>"userid is empty"); //用户id为空 echo json_encode($result); exit; } if(empty($orderid)){ $result=array('err_no' =>1001,'err_msg'=>"orderid is empty"); //跟单id为空 echo json_encode($result); exit; } $db = M( "order" ); $fix = C( "DB_PREFIX" ); $table = $fix."order"; $table2 = $fix."follow_order"; $page_size = 1; //每页显示记录数 //$count = count( $db -> field('art_id') -> where( "art_public='1'" ) -> select() );//记录总数 //查询满足条件的总页数 $data = $db -> field( "$table.id,$table.name,$table.remark as o_remark,$table2.time,$table2.remark as f_remark" ) -> join( "$table2 on $table.id=$table2.order_id" ) -> where( "$table.userid = '$userid' and $table.id = '$orderid' " ) -> order( "$table.id" ) -> select(); $count = count($data); $Page = new Page($count, 1); $data = $db -> field( "$table.id,$table.name,$table.remark as o_remark,$table2.time,$table2.remark as f_remark" ) -> join( "$table2 on $table.id=$table2.order_id" ) -> where( "$table.userid = '$userid' and $table.id = '$orderid' " ) -> order( "$table.id" ) -> limit($Page->firstRow.",".$Page->listRows) -> select(); if($data){ $result=array('err_no' =>1,'err_msg'=>"success",'data'=>$data,'TotalPages'=>$Page->getTotalPages(),'count'=>$count); //调用行业资讯列表成功,并返回总页数 (存在数据) echo json_encode($result); exit; }else{ $result=array('err_no' =>0,'err_msg'=>"order is empty"); //调用失败 (不存在数据) echo json_encode($result); exit; } //var_dump($order->getlastsql()); }