Я подключаю гибридное приложение к API веб-приложения для запроса определенных данных после поискового запроса пользователя. Я использую пользовательский интерфейс Onsen для создания приложения.
Код API на стороне сервера должен возвращать продавца, которого пользователь искал, по его имени. Результатом должен быть только 1 продавец (название ресторана)
public function actionSearchMerchant()
{
if (!isset($this->data['merchant'])){
$this->msg=$this->t("Restaurant Name is required");
$this->output();
}
if (isset($_GET['debug'])){
dump($this->data);
}
if ( !empty($this->data['merchant'])){
$DbExt=new DbExt;
$DbExt->qry("SET SQL_BIG_SELECTS=1");
$total_records=0;
$data='';
$and="AND status='active' AND is_ready='2' ";
$services_filter='';
if (isset($this->data['services'])){
$services=!empty($this->data['services'])?explode(",",$this->data['services']):false;
if ($services!=false){
foreach ($services as $services_val) {
if(!empty($services_val)){
$services_filter.="'$services_val',";
}
}
$services_filter=substr($services_filter,0,-1);
if(!empty($services_filter)){
$and.=" AND service IN ($services_filter)";
}
}
}
$filter_cuisine='';
if (isset($this->data['cuisine_type'])){
$cuisine_type=!empty($this->data['cuisine_type'])?explode(",",$this->data['cuisine_type']):false;
if ($cuisine_type!=false){
$x=1;
foreach (array_filter($cuisine_type) as $cuisine_type_val) {
if ( $x==1){
$filter_cuisine.=" LIKE '%\"$cuisine_type_val\"%'";
} else $filter_cuisine.=" OR cuisine LIKE '%\"$cuisine_type_val\"%'";
$x++;
}
if (!empty($filter_cuisine)){
$and.=" AND (cuisine $filter_cuisine)";
}
}
}
$rname=$this->data['merchant'];
$stmt="SELECT * FROM
{{view_merchant}}
WHERE
restaurant_name LIKE '%\"$rname\"%'
SELECT a.*,count(*) as total_records FROM
{{view_merchant}} a
WHERE
restaurant_name LIKE '%\"$rname\"%'
$and
LIMIT 0,100
";if (isset($_GET['debug'])){
dump($stmt);
}
if ( $res=$DbExt->rst($stmt)){
$stmtc="SELECT FOUND_ROWS() as total_records";
if ($resp=$DbExt->rst($stmtc)){
$total_records=$resp[0]['total_records'];
}
$this->code=1;
$this->msg=$this->t("Successful");
foreach ($res as $val) {
$minimum_order=getOption($val['merchant_id'],'merchant_minimum_order');
if(!empty($minimum_order)){
$minimum_order=displayPrice(getCurrencyCode(),prettyFormat($minimum_order));
}
$delivery_fee=getOption($val['merchant_id'],'merchant_delivery_charges');
if (!empty($delivery_fee)){
$delivery_fee=displayPrice(getCurrencyCode(),prettyFormat($delivery_fee));
}
/*check if mechant is open*/
$open=AddonMobileApp::isMerchantOpen($val['merchant_id']);
/*check if merchant is commission*/
$cod=AddonMobileApp::isCashAvailable($val['merchant_id']);
$online_payment='';
$tag='';
$tag_raw='';
if ($open==true){
$tag=$this->t("open");
$tag_raw='open';
if ( getOption( $val['merchant_id'] ,'merchant_close_store')=="yes"){
$tag=$this->t("close");
$tag_raw='close';
}
if (getOption( $val['merchant_id'] ,'merchant_preorder')==1){
$tag=$this->t("pre-order");
$tag_raw='pre-order';
}
} else {
$tag=$this->t("close");
$tag_raw='close';
if (getOption( $val['merchant_id'] ,'merchant_preorder')==1){
$tag=$this->t("pre-order");
$tag_raw='pre-order';
}
}$data[]=array(
'merchant_id'=>$val['merchant_id'],
'restaurant_name'=>$val['restaurant_name'],
'address'=>$val['street']." ".$val['city']." ".$val['state']." ".$val['post_code'],
'ratings'=>Yii::app()->functions->getRatings($val['merchant_id']),
'cuisine'=>AddonMobileApp::prettyCuisineList($val['cuisine']),
'delivery_fee'=>$delivery_fee,
'minimum_order'=>$minimum_order,
'delivery_est'=>getOption($val['merchant_id'],'merchant_delivery_estimation'),
'is_open'=>$tag,
'tag_raw'=>$tag_raw,
'payment_options'=>array(
'cod'=>$cod,
'online'=>$online_payment
),
'logo'=>AddonMobileApp::getMerchantLogo($val['merchant_id']),
'offers'=>AddonMobileApp::getMerchantOffers($val['merchant_id'])
);
}
$this->details=array(
'total'=>$total_records,
'data'=>$data
);
} else $this->msg=$this->t("No restaurant found");
} else $this->msg=$this->t("Error has occurred failed restaurant info");
} else $this->msg=$this->t("Restaurant Name is required");
$this->output();
}
По сути, я отправляю из приложения имена параметров «торговец», которые должен получить API, и выполняет поиск таблицы в базе данных с именем «view_merchant», столбец «restaurant_name», сравнивает имя, запрошенное в базе данных, и возвращает его обратно приложение как найдено.
РЕДАКТИРОВАТЬ Я добавил функцию JS
var search_restaurant;
var search_cuisine;
var search_food;
$("#r").val( getStorage("search_restaurant") );
$("#c").val( getStorage("search_cuisine") );
$("#f").val( getStorage("search_food") );
function searchMerchantName()
{
var r = $('#r').val();
/*clear all storage*/
setStorage("search_restaurant",r);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(r!=""){
var options = {
merchant:r,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchMerchants.html',options);
} else{
onsenAlert( getTrans('Restaurant Name is required','merchant_is_required') );
}
}
function searchCuisine()
{
var c = $('#c').val();
/*clear all storage*/
setStorage("search_cuisine",c);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(c!=""){
var options = {
cuisine:c,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchCuisine.html',options);
} else{
onsenAlert( getTrans('Cuisine Type is required','cuisine_is_required') );
}
}
function searchFood()
{
var f = $('#f').val();
/*clear all storage*/
setStorage("search_food",f);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(f!=""){
var options = {
foodname:f,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchFood.html',options);
} else{
onsenAlert( getTrans('Food Name is required','foodname_is_required') );
}
}
case "searchmerchant-page":
$("#search-text").html( getStorage("search_restaurant") );
callAjax("searchmerchant","merchant="+ getStorage("search_restaurant") );
break;
case "searchcuisine-page":
$("#search-text").html( getStorage("search_cuisine") );
callAjax("searchcuisine","cuisine="+ getStorage("search_cuisine") );
break;
case "searchfood-page":
$("#search-text").html( getStorage("search_food") );
callAjax("searchfood","foodname="+ getStorage("search_food") );
break;
case "page-home":
geoComplete();
search_address=getStorage("search_address");
if (typeof search_address === "undefined" || search_address==null || search_address=="" ) {
} else {
setTimeout('$("#s").val(search_address)', 1000);
}
translatePage();
$("#s").attr("placeholder", getTrans('Street Address,City,State','home_search_placeholder') );
//Added for Restaurant Name Search
search_restaurant=getStorage("search_restaurant");
if (typeof search_restaurant === "undefined" || search_restaurant==null || search_restaurant=="" ) {
} else {
setTimeout('$("#r").val(search_restaurant)', 1000);
}
translatePage();
$("#r").attr("placeholder", getTrans('Restaurant Name','restaurant_search_placeholder') );
//Added for Cuisine Type
search_cuisine=getStorage("search_cuisine");
if (typeof search_cuisine === "undefined" || search_cuisine==null || search_cuisine=="" ) {
} else {
setTimeout('$("#c").val(search_cuisine)', 1000);
}
translatePage();
$("#c").attr("placeholder", getTrans('Cuisine Type','cuisine_search_placeholder') );
//Added for Food Type
search_food=getStorage("search_food");
if (typeof search_food === "undefined" || search_food==null || search_food=="" ) {
} else {
setTimeout('$("#f").val(search_food)', 1000);
}
translatePage();
$("#f").attr("placeholder", getTrans('Food Name','food_search_placeholder') );
break;
function searchResultCallBack(address)
{
search_address=address;
}
function searchMerchantsCallBack(merchant)
{
search_restaurant=merchant;
}
function searchCuisineCallBack(cuisine)
{
search_cuisine=cuisine;
}
function searchFoodCallBack(foodname)
{
search_food=foodname;
}
Ваш оператор SQL будет:
SELECT * FROM view_merchant WHERE lower(restaurant_name)=?
Вам захочется toLowerCase()
ваше переданное значение $this->data['merchant']
так что вы находите ресторан независимо от корпуса. Единственная проблема заключается в том, что это вернет несколько записей, если есть записи с одинаковым именем.
Других решений пока нет …