1], [['limit'], 'integer'], [['limit'], 'default', 'value' => 20], ]; } public function search() { if (!$this->validate()) { return [ 'code' => 1, 'msg' => $this->getErrorSummary(false)[0] ]; } $shop_table_name = Shop::tableName(); $store_id = get_store_id(); $count_sql = 'SELECT count(1) AS total FROM '. $shop_table_name; $count_sql .= ' WHERE store_id = ' .$store_id. ' AND is_delete = 0 '; if ($this->keyword) { $count_sql .= ' AND name LIKE "%'.$this->keyword.'%"'; } $count_sql = \Yii::$app->db->quoteSql($count_sql); $count = \Yii::$app->db->createCommand($count_sql, [ ':store_id' => $this->store_id, ])->queryScalar(); $latitude = $this->latitude ? $this->latitude : 0; $longitude = $this->longitude ? $this->longitude : 0; $sql = "SELECT *, acos(cos({$latitude}*pi()/180 )*cos(latitude*pi()/180)*cos({$longitude}*pi()/180 -longitude*pi()/180)+sin({$latitude}*pi()/180 )*sin(latitude*pi()/180))*6370996.81 as distance FROM {$shop_table_name} WHERE ((`store_id`={$store_id}) AND (`is_delete`=0)) "; if ($this->keyword) { $sql .= " AND (`name` like '%{$this->keyword}%') "; } $sql .= ' ORDER BY distance ASC'; $pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit, 'page' => $this->page - 1]); $sql .= ' LIMIT ' . $pagination->offset . ',' . $pagination->limit; $sql = \Yii::$app->db->quoteSql($sql); $list = \Yii::$app->db->createCommand($sql, [ ':latitude' => $latitude, ':longitude' => $longitude, ':store_id' => $store_id, ])->queryAll(); foreach ($list as $index => $item) { $list[$index]['score'] = (int)$item['score']; $list[$index]['distance'] = self::distance($item['distance']); } return [ 'code' => 0, 'msg' => 'success', 'data' => [ 'list' => $list, 'page_count' => $pagination->pageCount, 'row_count' => $count ] ]; } private static function distance($distance) { if ($distance == -1) { return -1; } if ($distance > 1000) { $distance = round($distance / 1000, 2) . 'km'; } else { $distance = round($distance, 2); $distance .= 'm'; } return $distance; } }