簡體   English   中英

連接 Function 用於將一個表中的字段值與另一表匹配

[英]Join Function used to match value of field in one table with other table

當表中的字段值與另一個表的字段中的值匹配時,我正在嘗試顯示字段值。

就像我正在創建一個下拉字段。 這里基於汽車 Model 下拉菜單。 像法拉利一樣 Model 用戶在下拉列表中選擇了表 newcar_products 下的 prod_name 然后其變體如 Portnifo、superfast、488 應顯示在 Variant 字段下。

但是到目前為止發生的事情 - 無論 model 選擇法拉利、本田還是大眾汽車 - 變體都會顯示完整的變體列表,如 polo、jazz、portnifo、accord、passat 存儲在表 newcar_variants 的 v_name 中。 我希望變量 v_name 應該只顯示表 A 中的 v_prod_id 與表 B 中的 id 匹配

就像,我已經創建了這兩個函數,其中第一個 function 的下拉菜單運行良好

      <?php    
        function model_drop_down(){
            $database = JFactory::getDBO();
            $sql = "SELECT * from #__newcar_products where state='1'  order by prod_name Asc";
            $database->setQuery($sql);
            $rows = $database->loadObjectList();
            $list="";
            foreach($rows as $row){
                $list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->prod_name."</option>";
            }
            return $list;
        }


       function variant_drop_down(){
    $database = JFactory::getDBO();
    $sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
    and a.state='1' where  1 order by a.v_prod_id asc";
    $database->setQuery($sql);
    $rows = $database->loadObjectList();
    $list="";
    foreach($rows as $row){
        $list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->v_name."</option>";
    }
    return $list;
    } ?>

     <div class="common-box">
        <div class="common-box-left">Car Model*</div>
        <div class="common-box-right">
          <div id="txtHint">
          <select name="model"  class="list-box-big"  id="model"  lang="MUST" title="Model" style="width:245px; height:25px;">
              <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
<?php echo model_drop_down();?>
            </select>
          </div>
        </div>
      </div>
      <!--box end-->
      <!--box start-->
      <div class="common-box">
        <div class="common-box-left">Sub Model*</div>
        <div class="common-box-right">
          <div id="txtHintVariant">
          <select name="variant" class="list-box" id="brand"  lang="MUST" title="Brand">
                <option value="" selected="selected" style='padding-left:10px;'>Select Variant</option>
                <?php echo variant_drop_down();?>
            </select>
          </div>

繼承人兩個表的架構在此處輸入圖像描述

截至目前,顯示所有型號和所有變體名稱的字段。 現在在變體的第二個字段中發生了什么,它顯示存儲在 v_name 中的所有值,而不僅僅是那些在 v_name 下的值,其中 newcar_variants 中的 v_prod_id 與 newcar_products 中的 id 匹配

我認為需要一種方法第1步當用戶select Model從第一個字段下拉時,字段id的varle需要存儲在newcar_products

步驟 2 然后在 select 變體的第二個字段中,當用戶 select 在第一個字段中下拉 model 時。 存儲在 newcar_products 中的“id”值應與第二個表 newcar_variants 中的 v_prod_id 匹配,因此要在匹配“v_name”中顯示的變體列表

如何創建 function 以實現所需。 任何人都可以幫助,新手這將是一個很好的學習。 謝謝

在存根數據庫連接后,我獲取了您的代碼並添加了缺少的功能。

您可以使用下面的鏈接現場試用:

https://code.sololearn.com/wm6EGyHmt5cj

只需單擊綠色的“運行”按鈕,您就可以在下拉菜單中選擇 select 和 model 並查看相應過濾的變體。

這也是完整的代碼(以防此鏈接過期):

<?

function getModel($id, $name) {
    $row = new stdClass();
    $row->id = $id;
    $row->prod_name = $name;
    return $row;
}

function getVariant($id, $name, $modelId) {
    $row = new stdClass();
    $row->id = $id;
    $row->v_name = $name;
    $row->v_prod_id = $modelId;
    return $row;
}

function model_drop_down(){
    //---YOUR CODE COMMENTED BELOW---
    // $database = JFactory::getDBO();
    // $sql = "SELECT * from #__newcar_products where state='1'  order by prod_name Asc";
    // $database->setQuery($sql);
    // $rows = $database->loadObjectList();
    //---END OF YOUR COMMENTED CODE---

    //---MY DB STUB BELOW
    $rows = [];
    array_push($rows, getModel(0, 'Ferrari'));
    array_push($rows, getModel(1, 'Honda'));
    array_push($rows, getModel(2, 'Volkswagen'));
    //---END OF MY DB STUB

    $list="";
    foreach($rows as $row){
        $list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->prod_name."</option>";
    }
    return $list;
}


function variant_drop_down(){
    //---YOUR CODE COMMENTED BELOW---
    // $database = JFactory::getDBO();
    // $sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
    // and a.state='1' where  1 order by a.v_prod_id asc";
    // $database->setQuery($sql);
    // $rows = $database->loadObjectList();
    //---END OF YOUR COMMENTED CODE---

    //---MY DB STUB BELOW
    $rows = [];
    array_push($rows, getVariant(0, '250 GTO', 0));
    array_push($rows, getVariant(1, 'F430', 0));
    array_push($rows, getVariant(2, 'F40', 0));
    array_push($rows, getVariant(3, 'Civic', 1));
    array_push($rows, getVariant(4, 'CR-V', 1));
    array_push($rows, getVariant(5, 'Golf', 2));
    array_push($rows, getVariant(6, 'Polo', 2));
    array_push($rows, getVariant(7, 'Passat', 2));
    //---END OF MY DB STUB

    $list="";
    foreach($rows as $row){
        $list.="<option value='".$row->id."' data-v_prod_id='".$row->v_prod_id."' style='padding-left:10px;'>".$row->v_name."</option>";
    }
    return $list;
}

?>

<div class="common-box">
    <div class="common-box-left">Car Model*</div>
    <div class="common-box-right">
        <div id="txtHint">
            <select name="model" class="list-box-big" id="model" lang="MUST" title="Model" style="width:245px; height:25px;">
                <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
                <?php echo model_drop_down();?>
            </select>
        </div>
    </div>
</div>
<!--box end-->
<!--box start-->
<div class="common-box">
    <div class="common-box-left">Sub Model*</div>
    <div class="common-box-right">
        <div id="txtHintVariant">
            <select name="variant" class="list-box" id="brand" lang="MUST" title="Brand">
                <option value="" selected="selected" style='padding-left:10px;'>Select Variant</option>
                <?php echo variant_drop_down();?>
            </select>
        </div>
    </div>
</div>

<script>
//wait for html DOM loaded
document.addEventListener("DOMContentLoaded", function(event) {
    //listen to "model dropdown changed by user" event
    document.getElementById("model").onchange = function filterVariants(){

        //get the currently selected model
        const selectedModelId = document.getElementById('model').value;

        if(selectedModelId=="") {
        //if no model is selected, show all the variants (set display=block for all options)

            for(option of document.querySelectorAll('#brand>option')) {
                option.style.display='block';
            }

        } else {
        //if a model is selected, show the only variants having 'data-v_prod_id' attribute equal to the id of the selected model, plus the defaul "Select Variant" option

            for(option of document.querySelectorAll('#brand>option')) {
                if(option.getAttribute('data-v_prod_id')==selectedModelId) {
                    //variant from the selected model => show the option
                    option.style.display='block';
                } else if(option.value=="") {
                    //default option (the one with "Select Variant") => show it
                    option.style.display='block';
                    option.selected=true;
                } else {
                    //else, it's a variant from another model => hide it
                    option.style.display='none';
                }
            }
        }

        //reset the variant dropdown to default "Select Variant" value
        document.querySelector('#brand>option[value=""]').selected=true

    };
});
</script>

這是我的更改的描述:

1. 樣機數據

當然,我無權訪問您的數據庫,因此我將 SQL 連接和查詢替換為幾行代碼以創建模型數據:

function getModel generates a model object that looks like a SQL model result row

function getVariant生成一個變體 object 看起來像 SQL 變體結果行

然后在您的model_drop_down function 中,我手動創建數據以填充$rows以使$rows看起來與您的 SQL 查詢的結果相同:

array_push($rows, getModel(0, 'Ferrari'));
array_push($rows, getModel(1, 'Honda'));
array_push($rows, getModel(2, 'Volkswagen'));

例如,最后一行意味着我正在創建一個模型 model,id=2 和 name='Volkswagen'

然后我對你的variant_drop_down中的變體做了同樣的事情:

array_push($rows, getVariant(0, '250 GTO', 0));
array_push($rows, getVariant(1, 'F430', 0));
array_push($rows, getVariant(2, 'F40', 0));
array_push($rows, getVariant(3, 'Civic', 1));
array_push($rows, getVariant(4, 'CR-V', 1));
array_push($rows, getVariant(5, 'Golf', 2));
array_push($rows, getVariant(6, 'Polo', 2));
array_push($rows, getVariant(7, 'Passat', 2));

例如,最后一行意味着我正在創建一個 id=7、name='Passat' 和 v_prod_id=2(即大眾汽車)的模型變體。

好的,現在我已經為你的數據庫存根了,我們可以開始編碼了!


2. 更改 SQL 變體查詢以獲取所有變體和 select 'v_prod_id' 字段

variant_drop_down只會被調用一次(php是服務端語言,運行一次會渲染頁面的html代碼,不會再次運行),所以我們需要一次獲取所有數據,並取回v_prod_id字段以記住哪個變體屬於哪個 model(我們將在接下來的步驟中使用此信息)

因此,我們將更改查詢中的兩件事:

  1. 刪除 JOIN ON a.v_prod_id = b.id
  2. 在 SELECT 子句中添加 a.v_prod_id

所以從這里:

SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id and a.state='1' where  1 order by a.v_prod_id asc

你最終會得到這樣的東西:

SELECT a.id, a.v_name, a.v_prod_id FROM #__newcar_variants a where a.state='1' order by a.v_prod_id asc

3. 在變體下拉列表的每個項目上添加 v_prod_id

這是通過在代碼中添加data-v_prod_id='".$row->v_prod_id."'來完成的。

現在,變體下拉列表的 html 代碼如下所示:

<select name="variant" class="list-box" id="brand" lang="MUST" title="Brand">
    <option value="" selected="selected">Select Variant</option>
    <option value="0" data-v_prod_id="0">250 GTO</option>
    <option value="1" data-v_prod_id="0">F430</option>
    <option value="2" data-v_prod_id="0">F40</option>
    <option value="3" data-v_prod_id="1">Civic</option>
    <option value="4" data-v_prod_id="1">CR-V</option>
    <option value="5" data-v_prod_id="2">Golf</option>
    <option value="6" data-v_prod_id="2">Polo</option>
    <option value="7" data-v_prod_id="2">Passat</option>
</select>

如您所見,我們在每個變體上都有 data-v_prod_id。

現在,對於變體下拉列表中的每個選項,我們知道它與哪個 model 相關。

因此,使用 javascript,每次用戶更改 model 時,我們可以過濾顯示的變體,其中 v_prod_id 等於所選 model。


4.使用javascript進行動態變體過濾

每次用戶更改 model 時,我們都會相應地過濾變體下拉列表。

這是執行此操作的腳本,我在每一行都添加了注釋以解釋詳細信息:

<script>
//wait for html DOM loaded
document.addEventListener("DOMContentLoaded", function(event) {
    //listen to "model dropdown changed by user" event
    document.getElementById("model").onchange = function filterVariants(){

        //get the currently selected model
        const selectedModelId = document.getElementById('model').value;

        if(selectedModelId=="") {
        //if no model is selected, show all the variants (set display=block for all options)

            for(option of document.querySelectorAll('#brand>option')) {
                option.style.display='block';
            }

        } else {
        //if a model is selected, show the only variants having 'data-v_prod_id' attribute equal to the id of the selected model, plus the defaul "Select Variant" option

            for(option of document.querySelectorAll('#brand>option')) {
                if(option.getAttribute('data-v_prod_id')==selectedModelId) {
                    //variant from the selected model => show the option
                    option.style.display='block';
                } else if(option.value=="") {
                    //default option (the one with "Select Variant") => show it
                    option.style.display='block';
                    option.selected=true;
                } else {
                    //else, it's a variant from another model => hide it
                    option.style.display='none';
                }
            }
        }

        //reset the variant dropdown to default "Select Variant" value
        document.querySelector('#brand>option[value=""]').selected=true

    };
});
</script>

希望我的回答能讓你滿意。

同樣,您可以通過單擊此鏈接進行現場試用: https://code.sololearn.com/wm6EGyHmt5cj然后單擊綠色的“運行”按鈕。

<optgroup>這個 HTML 標簽可以幫助你嗎? https://developer.mozilla.org/fr/docs/Web/HTML/Element/Optgroup

那么你只有一個數據庫查詢:

function variant_drop_down(){
    $database = JFactory::getDBO();
    $sql = "SELECT b.prod_name, a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
    and a.state='1' where  1 order by a.v_prod_id asc";
    $database->setQuery($sql);
    $rows = $database->loadObjectList();
    $list="";
    $label=null;
    foreach($rows as $row){
        if ($label!=$row->prod_name) {
            if (null!==$label) {
                $list.="</optgroup>";
            }
            $label=$row->prod_name;
            $list.='<optgroup label="'.$label.'">';
        }
        $list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->v_name."</option>";
    }
    if (null!==$label) {
        $list.="</optgroup>";
    }
    return $list;
    } ?>

無論您試圖實現什么,都不能僅通過 PHP 來完成。 您必須使用 JQuery/JavaScript 來獲得結果。

如果您的模型和變體是 static 則使用文森特的代碼,但要進行動態操作,您必須使用以下代碼。

我只是給出一個想法,你必須鍛煉基於 ajax 的解決方案的確切解決方案。

這將是第一個退出選項:

 <select name="model" id="model">
       <?php echo model_drop_down();?>
 </select>

 <select name="variant" id="variant">
 </select>

您的 Jquery 代碼將如下所示:

$(document).ready(function() {
    $('#model').change(function() {
        $.ajax({
            type : 'POST',
            url : 'variant.php',
            dataType : 'json',
            data: {
                model : $('#model').val()
            },
            success: function(data){
                $('#variant >option').remove();
                var s= document.getElementById('model');
                s.options[s.options.length]= new Option('Kindly Select Variant', '');
                $.each(data.variant, function() {
                    s.options[s.options.length]= new Option(this, this);
                })
            }
        });
    });
})

您的變體.php 文件

//I don't know the exact variant value but the post value is the mode id number here
// $_POST["model"] = $row->id

$database = JFactory::getDBO();

//Create the query to exact the only variants of model number here

$sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products 
    b ON a.v_prod_id = b.id and a.state=$_POST["model"] where  1 order by a.v_prod_id asc";

$database->setQuery($sql);
$rows = $database->loadObjectList();
foreach($rows as $row){
    $t[]= $row->v_name;
}
$return['variant']=$t;
echo json_encode($return);

這不是確切的解決方案,而是一個基本想法,您必須根據需要進行更改。 此示例可能包含一些小錯誤,因為它未運行

如果用戶根據加載的汽車變體選擇 var model,我更喜歡基於 ajax 的解決方案。關聯

您也可以 go 用於基於 php 陣列的解決方案,讓我知道我也可以向您展示,但我更喜歡 ajax 解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM