2017-11-18 203 views
1

我想將下面的自動完成代碼集成到我的CakePHP代碼中。主要我想從數據庫(製造商+產品,例如:BMW X5)中取出數據,而不是從以下代碼中的數組availableTags中獲取數據。如何在cakephp中實現搜索欄自動完成

我不是CakePHP的專家,所以我該如何將CakePHP數據庫函數availableTags替換爲數組?

產品表列:ID,PRODUCT_NAME,版本,MANUFACTURER_ID,類別ID

製造商表列:ID,製造商

Search.html

<!doctype html> 
    <html lang="en"> 
    <head> 
     <meta charset="utf-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
     <title>jQuery UI Autocomplete - Default functionality</title> 
     <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> 


     <?php App::import('Controller','Products');App::import('Controller','Manufacturers'); 

<link rel="stylesheet" href="/resources/demos/style.css"> 
     <script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
     <script> 
     $(function() { 
     var availableTags = [ 
      "ActionScript", 
      "AppleScript", 
      "Asp", 
      "BASIC", 
      "C", 
      "C++", 
      "Clojure", 
      "COBOL", 
      "ColdFusion", 
      "Erlang", 
      "Fortran", 
      "Groovy", 
      "Haskell", 
      "Java", 
      "JavaScript", 
      "Lisp", 
      "Perl", 
      "PHP", 
      "Python", 
      "Ruby", 
      "Scala", 
      "Scheme" 
     ]; 
     $("#tags").autocomplete({ 
      source: availableTags 
     }); 
     }); 
     </script> 
    </head> 
    <body> 

    <div class="ui-widget"> 
     <label for="tags">Tags: </label> 
     <input id="tags"> 
    </div> 

產品控制器

public function suggestion() { 
     $this->autoRender = false; 

     $query = $this->params['url']['term']; 

     $return_arr = array(); 
     $products = $this->Product->find('all', array('fields' => array('DISTINCT (Product.product_name) AS product_name'),'conditions' => array('Product.product_name LIKE' => $query.'%'))); 

     foreach($products as $product) { 
      $return_arr[] = $product['Product']['product_name']; 
     } 


     echo json_encode($return_arr); 

    }?> 
製造商控制器
public function suggestion() { 
      $this->autoRender = false; 

      $query = $this->params['url']['term']; 

      $return_arr = array(); 
      $manufacturers = $this->Manufacturer->find('all', array('fields' => array('Manufacturer.manufacturer'),'conditions' => array('Manufacturer.manufacturer LIKE' => $query.'%'))); 

      foreach($manufacturers as $manufacturer) { 
       $return_arr[] = $manufacturer['Manufacturer']['manufacturer']; 
      } 


      echo json_encode($return_arr); 

     }?> 

回答

0

可以製造商表綁定與產品表,然後在產品控制器,當您獲取產品,您可以使用虛擬字段值組合

+0

好可以請你讓我知道,這兩個表中的字段? –

相關問題