field($field) ->order($order) ->paginate(['list_rows' => $pageSize, 'query' => request()->param()]); $page = $list->render(); $data['list'] = $list->toArray()['data']; $data['count'] = $list->total(); $data['page'] = $page; return $data; } /** * 获取所有列表(不分页) * @param array $where 查询条件 * @param string $field 查询字段 * @param string $order 排序规则 * @param string $limit 限制条数 * @return \think\Collection */ public static function getAllList($where = [], $field = '*', $order = 'create_time desc', $limit = '0') { $data = self::where($where) ->field($field) ->order($order) ->limit($limit) ->select(); return $data; } /** * 获取单条数据 * @param array $where 查询条件 * @param string $field 查询字段 * @return array|Model|null */ public static function getInfo($where = [], $field = '*') { $data = self::where($where) ->field($field) ->find(); return $data; } /** * 获取热销商品 */ public static function getHotProducts($limit = 10, $field = '*') { return self::where('status', 1) ->where('is_hot', 1) ->field($field) ->order('sales desc') ->limit($limit) ->select(); } /** * 获取新品商品 */ public static function getNewProducts($limit = 10, $field = '*') { return self::where('status', 1) ->where('is_new', 1) ->field($field) ->order('create_time desc') ->limit($limit) ->select(); } /** * 获取推荐商品 */ public static function getRecommendProducts($limit = 10, $field = '*') { return self::where('status', 1) ->where('is_recommend', 1) ->field($field) ->order('create_time desc') ->limit($limit) ->select(); } /** * 根据分类名称获取商品 * @param string $categoryName 分类名称 * @param int $limit 限制条数 * @param string $field 查询字段 * @return \think\Collection */ public static function getProductsByCategory($categoryName, $limit = 10, $field = '*') { return self::where('status', 1) ->where('category_name', 'like', "%{$categoryName}%") ->field($field) ->order('create_time desc') ->limit($limit) ->select(); } /** * 搜索商品 */ public static function searchProducts($keyword, $field = '*', $pageSize = 15) { return self::where('status', 1) ->where(function ($query) use ($keyword) { $query->where('product_name', 'like', "%{$keyword}%") ->whereOr('product_desc', 'like', "%{$keyword}%") ->whereOr('category_name', 'like', "%{$keyword}%"); }) ->field($field) ->order('create_time desc') ->paginate(['list_rows' => $pageSize, 'query' => request()->param()]); } /** * 更新库存 * @param int $id 商品ID * @param int $num 减少的数量 * @return bool */ public static function updateStock($id, $num) { return self::where('id', $id) ->where('stock', '>=', $num) ->dec('stock', $num) ->inc('sales', $num) ->update(); } /** * 根据条件获取商品列表并按价格排序 * @param array $where 查询条件 * @param string $order 排序规则 asc-升序 desc-降序 * @param int $pageSize 每页数量 * @return array */ public static function getListByPrice($where = [], $order = 'asc', $pageSize = 15) { $orderRule = $order == 'asc' ? 'price asc' : 'price desc'; return self::getList($where, '*', $orderRule, $pageSize); } }