tp5 使用paginate分页获取数据对象之后 如何对对象进行数据添加
大家都知道,在使用tp5的paginate获取分页数据之后,得到的是一个数据对象,但有时会碰到要对数据对象进行二次加工的情况,下面是解决此类问题的方法
1、直接在查询语句中利用MySQL函数
举例一:
1、将获取到的图片由相对地址拼接上域名,形成绝对地址
$yu = YU();
return $this->field('orderid,productid,attrid,concat("'.$yu.'", logo) logo,title')
->where(['orderid'=>$OrderId])->paginate(10);
2、将时间戳转换成所需要的日期格式
return $this->where($where)->with('user')
->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d') createtime")
->order('createtime desc')
->select();
关于时间戳与日期转换,请参考MySQL时间戳与日期互相转换
举例二:每个商品有不同的规格数据,统计每个商品所有规格的总库存
$products = Db::name('product p')
->field('itemid,name,m_price,price,logo,sale_num,sort,is_sale,is_floor,addtime,update_time')
->field('(select sum(stock) from xf_product_attr a where a.product_id = p.itemid) stock_all')
->whereOr($keywordComplex)
->where($where)
->order('itemid asc list_order asc')
->paginate(10,false,[
'query'=>[
'keyword' =>$keyword,
'is_sale' =>$is_sale,
'is_floor' =>$is_floor,
'category' =>$category,
]
]);
举例三:获得某种商品券的兑换总数,使用左连接
return $this->with('shop')
->alias('p')
->join('order o','p.itemid = o.pro_id and o.status=2','left')
->whereOr($whereOr)
->where($where)
->field('p.itemid,p.name,p.title,p.avatar,p.point,p.status,p.addtime,p.list_order, p.shop_id,p.check_status,count(*)')
->order('p.addtime desc')
->paginate(10,false,$query);
可以看到生成的sql的语句是
[ SQL ] SELECT p.itemid,p.name,p.title,p.avatar,p.point,p.status,p.addtime,p.list_order, p.shop_id,p.check_status,count(*) FROM `xf_product` `p`
LEFT JOIN `xf_order` `o` ON `p`.`itemid`=o.pro_id and o.status=2 ORDER BY `p`.`addtime` DESC LIMIT 0,10 [ RunTime:0.000000s ]
也可使用子查询,不过效率就下来了
return $this->with('shop')
->alias('p')
->whereOr($whereOr)
->where($where)
->field('*,(select count(*) from xf_order o where o.pro_id = p.itemid and o.status = 2)')
->order('p.addtime desc')
->paginate(10,false,$query);
生成的sql是这样的:
[ SQL ] SELECT *,(select count(*) from xf_order o where o.pro_id = p.itemid and o.status = 2)
FROM `xf_product` `p` ORDER BY `p`.`addtime` DESC LIMIT 0,10 [ RunTime:0.014000s ]
2、还有一些复杂的,通过MySQL自带函数是实现不了的,此时可以将对象转换为数组,然后再处理
} else {
$products = Db::name('product p')
->field('itemid,name,m_price,price,logo,sale_num,sort,is_sale,is_floor,addtime,update_time')
->whereOr($keywordComplex)
->where($where)
->order('itemid asc list_order asc')
->paginate(10,false,[
'query'=>[
'keyword' =>$keyword,
'is_sale' =>$is_sale,
'is_floor' =>$is_floor,
'category' =>$category,
]
]);
} //查找商品自身的类别
$products->toArray();
foreach($products as $k=>$v){
$data = $v;
$data['category_id'] = Db::name('product_category_bind pb')
->view('category pc','id,name','pb.category_id = pc.id','left')
->where(['pb.product_id'=>$v['itemid']])
->select()->toArray();
$products->offsetSet($k,$data);
}