简体   繁体   English

连接 Function 用于将一个表中的字段值与另一表匹配

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

I am trying to display field values, when values of field in the table matches with the values in field of another table.当表中的字段值与另一个表的字段中的值匹配时,我正在尝试显示字段值。

Its like I am creating a drop down fields.就像我正在创建一个下拉字段。 Here basis the car Model dropdown.这里基于汽车 Model 下拉菜单。 Like Ferrari as Model chosen in dropdown by user as prod_name under table newcar_products then its variants like Portnifo, superfast,488 should be shown under Variant field.像法拉利一样 Model 用户在下拉列表中选择了表 newcar_products 下的 prod_name 然后其变体如 Portnifo、superfast、488 应显示在 Variant 字段下。

But whats happening as of now - irrespective of model selected whether Ferrari or Honda or Volkswagen - the variants displays the entire list of variants like polo, jazz,portnifo,accord,passat as stored in v_name in table newcar_variants.但是到目前为止发生的事情 - 无论 model 选择法拉利、本田还是大众汽车 - 变体都会显示完整的变体列表,如 polo、jazz、portnifo、accord、passat 存储在表 newcar_variants 的 v_name 中。 I want that variants v_name should be displayed only for v_prod_id in table A matches with id in table B我希望变量 v_name 应该只显示表 A 中的 v_prod_id 与表 B 中的 id 匹配

Like, i have created these 2 functions where first function of drop down are working perfectly就像,我已经创建了这两个函数,其中第一个 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>

Heres schema of both tables继承人两个表的架构在此处输入图像描述

As of now the fields displaying all models and name of all variants.截至目前,显示所有型号和所有变体名称的字段。 Whats happening now in second field of variant its displaying all value stored in v_name rather than only those under v_name where v_prod_id in newcar_variants matches with id in newcar_products现在在变体的第二个字段中发生了什么,它显示存储在 v_name 中的所有值,而不仅仅是那些在 v_name 下的值,其中 newcar_variants 中的 v_prod_id 与 newcar_products 中的 id 匹配

I think a way needed which Step 1 When a user select Model from drop down in the first field, the varle of field id needs to be stored in newcar_products我认为需要一种方法第1步当用户select Model从第一个字段下拉时,字段id的varle需要存储在newcar_products

Step 2 Then in second field of select variant, when the user select drop down of model in the first field.步骤 2 然后在 select 变体的第二个字段中,当用户 select 在第一个字段中下拉 model 时。 the value of 'id' as stored in newcar_products should match with the v_prod_id in the second table newcar_variants and thus the list of variants to be displayed in matching 'v_name'存储在 newcar_products 中的“id”值应与第二个表 newcar_variants 中的 v_prod_id 匹配,因此要在匹配“v_name”中显示的变体列表

How to create the function to achieve desired.如何创建 function 以实现所需。 Can anyone help, been novice this would be a great learning.任何人都可以帮助,新手这将是一个很好的学习。 thanks谢谢

I took your code and added the missing features, after stubbing the DB connection.在存根数据库连接后,我获取了您的代码并添加了缺少的功能。

You can try it live using the link below:您可以使用下面的链接现场试用:

https://code.sololearn.com/wm6EGyHmt5cj https://code.sololearn.com/wm6EGyHmt5cj

Just click the green "RUN" button and you will be able to select a model in the dropdown and to see the variants being filtered accordingly.只需单击绿色的“运行”按钮,您就可以在下拉菜单中选择 select 和 model 并查看相应过滤的变体。

And here is the full code as well (in case this link expires):这也是完整的代码(以防此链接过期):

<?

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>

Here is the description of my changes:这是我的更改的描述:

1. Mockup Data 1. 样机数据

Of course, I don't have access to your DB, so I replaced the SQL connection and query with a few lines of code to create mockup data:当然,我无权访问您的数据库,因此我将 SQL 连接和查询替换为几行代码以创建模型数据:

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

function getVariant generates a variant object that looks like a SQL variant result row function getVariant生成一个变体 object 看起来像 SQL 变体结果行

Then in your model_drop_down function, I manually created data to populate $rows in order to have $rows look the same than the result of your SQL query:然后在您的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'));

For instance, the last line means I'm creating a mockup model with id=2 and name='Volkswagen'例如,最后一行意味着我正在创建一个模型 model,id=2 和 name='Volkswagen'

Then I did the same with variants in your variant_drop_down function:然后我对你的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));

For instance, the last line means I'm creating a mockup variant with id=7, name='Passat' and v_prod_id=2 (which is Volkswagen).例如,最后一行意味着我正在创建一个 id=7、name='Passat' 和 v_prod_id=2(即大众汽车)的模型变体。

Ok, now I have stubbed your database, we can start coding!好的,现在我已经为你的数据库存根了,我们可以开始编码了!


2. Change the SQL variants query to get them all and select the 'v_prod_id' field 2. 更改 SQL 变体查询以获取所有变体和 select 'v_prod_id' 字段

The variant_drop_down function will be called only once (php is a server side language, it runs once to render the html code of the page, and is never run again), so we need to get all the data at once, and retrieve the v_prod_id field in order to memorize which variant belongs to which model (we'll use this information in the next steps) variant_drop_down只会被调用一次(php是服务端语言,运行一次会渲染页面的html代码,不会再次运行),所以我们需要一次获取所有数据,并取回v_prod_id字段以记住哪个变体属于哪个 model(我们将在接下来的步骤中使用此信息)

So we'll change 2 things in the query:因此,我们将更改查询中的两件事:

  1. Remove the JOIN ON a.v_prod_id = b.id删除 JOIN ON a.v_prod_id = b.id
  2. Add a.v_prod_id in the SELECT clause在 SELECT 子句中添加 a.v_prod_id

So from this:所以从这里:

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

You will end up with something like this:你最终会得到这样的东西:

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. Add the v_prod_id on each item of the variant dropdown 3. 在变体下拉列表的每个项目上添加 v_prod_id

This is done by adding data-v_prod_id='".$row->v_prod_id."' in your code.这是通过在代码中添加data-v_prod_id='".$row->v_prod_id."'来完成的。

Here is what the html code of the variant dropdown looks like, now:现在,变体下拉列表的 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>

As you can see, we have data-v_prod_id on each variant.如您所见,我们在每个变体上都有 data-v_prod_id。

Now, for each option in the variant dropdown, we know which model it's related to.现在,对于变体下拉列表中的每个选项,我们知道它与哪个 model 相关。

So, using javascript, each time the user will change the model, we can filter the displayed variants having v_prod_id equal to the selected model.因此,使用 javascript,每次用户更改 model 时,我们可以过滤显示的变体,其中 v_prod_id 等于所选 model。


4. Dynamic variant filtering using javascript 4.使用javascript进行动态变体过滤

Each time the user will change the model, we will filter the variant dropdown accordingly.每次用户更改 model 时,我们都会相应地过滤变体下拉列表。

This is the script to do it, I have put comments on each line to explain the details:这是执行此操作的脚本,我在每一行都添加了注释以解释详细信息:

<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>

I hope my answer satisfies you.希望我的回答能让你满意。

Again, you can try it live by clicking this link: https://code.sololearn.com/wm6EGyHmt5cj then clicking the green "RUN" button.同样,您可以通过单击此链接进行现场试用: https://code.sololearn.com/wm6EGyHmt5cj然后单击绿色的“运行”按钮。

<optgroup> May this HTML tag can help you? <optgroup>这个 HTML 标签可以帮助你吗? https://developer.mozilla.org/fr/docs/Web/HTML/Element/Optgroup https://developer.mozilla.org/fr/docs/Web/HTML/Element/Optgroup

Then you have only one DB query:那么你只有一个数据库查询:

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;
    } ?>

As whatever you are trying to achieve that would not be done through PHP alone.无论您试图实现什么,都不能仅通过 PHP 来完成。 You have to use JQuery/JavaScript to achieve the result.您必须使用 JQuery/JavaScript 来获得结果。

If your Models and Variants are static then use the code of Vincent but to do dynamic you have to use below code.如果您的模型和变体是 static 则使用文森特的代码,但要进行动态操作,您必须使用以下代码。

I am just giving the idea you have to workout the exact solution of ajax based solution.我只是给出一个想法,你必须锻炼基于 ajax 的解决方案的确切解决方案。

This would be first drop out option as:这将是第一个退出选项:

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

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

Your Jquery code would be like this:您的 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);
                })
            }
        });
    });
})

Your variant.php file您的变体.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);

It is not the exact solution but a basic idea more you have to do changes according to your needs.这不是确切的解决方案,而是一个基本想法,您必须根据需要进行更改。 This example may contain some minor error as it is not run此示例可能包含一些小错误,因为它未运行

I am preferring ajax based solution for this if user selects var model based on that car variant is loaded.如果用户根据加载的汽车变体选择 var model,我更喜欢基于 ajax 的解决方案。Link关联

Also you can go for php array based solution let me know i can you show you that also but I prefer ajax based solution for this.您也可以 go 用于基于 php 阵列的解决方案,让我知道我也可以向您展示,但我更喜欢 ajax 解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM