有一个需求,只返回有库存的物品,但是库存数量是根据入库和出库计算的,数据库是不存在这个字段的,请问分页查询的情况下,怎么去满足每次返回20条记录?
list($where, $alias, $limit, $order) = $this->queryBuilder();
$res = $this->model
->field($this->indexField)
->withJoin($this->withJoinTable, $this->withJoinType)
->alias($alias)
->where($where)
->order($order)
->paginate($limit)
->each(function ($item,$key) {
$product_in = Db::name('product_in')->where('product_id',$item['id'])->sum('quantity'); //该物品的入库数量
$product_out = Db::name('product_out')->where('product_id',$item['id'])->sum('quantity'); //该物品的出库数量
$item['stock'] = $product_in - $product_out; //这里是库存计算
});
$this->success('', [
'list' => $res->items(),
'total' => $res->total(),
'remark' => get_route_remark(),
]);
我能想到的就是用子查询,可以在数据库层面就解决掉,但是这种基本上都会出现 dependent subquery,查询效率很低,并不值当。
这种场景算是比较常见的,总会因为一些原因过滤掉一些数据的,导致缺少或者多出来一些数据,对于这种问题应该尽量先跟产品沟通,忽略掉这种问题,当然,也要避免一页一个产品都没有的情况。
或者想办法在数据添加这个字段,并且及时刷新(考虑时效),从在查询的时候使用 SQL 过滤掉,其他方案也类似。