如何在cakephp中实现搜索栏自动完成

How to implement Search bar Autocomplete in cakephp

我想将下面的自动完成代码集成到我的 CakePHP 代码中。主要是我想从数据库中提取数据(制造商+产品,例如:BMW X5)而不是下面代码中的数组availableTags

我不是 CakePHP 专家,所以如何将数组 availableTags 替换为 CakePHP 数据库函数?

产品 table 列:ID,product_name,版本,manufacturer_id,类别 ID

制造商 table 列: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);

        }?>

您可以将制造商 table 与产品 table 绑定,然后在产品控制器中获取产品时,您可以使用虚拟字段组合值