如何在Codeigniter中将选择查询添加到另一个选择查询中

w8biq8rn  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(87)

我有两个表如下图:

/* questions table */
|  q_id   |  q_title               |
| ------- | ---------------------- |
|  1      |  What is your name?    |
| ------- | ---------------------- |
|  2      |  What is your gender?  |
| ------- | ---------------------- |
|  ...    |                        |

/* options table */
|  o_id  |  o_title  |  o_question_id  |
| ------ | --------- | --------------- |
|  1     |  George   |  1              |
| ------ | --------- | --------------- |
|  2     |  Sarah    |  1              |
| ------ | --------- | --------------- |
|  3     |  Michael  |  1              |
| ------ | --------- | --------------- |
|  4     |  Male     |  2              |
| ------ | --------- | --------------- |
|  5     |  Female   |  2              |
| ------ | --------- | --------------- |
|  ...   |           |                 |

如何从以下两个表中进行选择:

1.你叫什么名字?

乔治
萨拉
米迦勒

2.您的性别是?

男性
女性

  • “JOIN”表示重复问题。*

我的代码哪里错了?
我的控制器:

/* controller */
$data['questions'] = $this->db->get('questions_tbl')->result();
$items_arr = array();
foreach ($data['questions'] as $option) {
    $items_arr[] = $this->db->where('o_question_id', $option->q_id)->get('options_tbl')->result();
}
$data['options'] = $items_arr;

而我的看法:

/* view */
<?php foreach ($questions as $q) { ?>
    <strong><?= $q->q_id ?>.<?= $q_title ?></strong>
    <?php foreach ($options as $o) { ?>
        <?php if ($o->o_question_id == $q->id) { ?>
            <p><?= $o->o_title ?></p>
        <?php } ?>
    <?php } ?>
<?php } ?>
eblbsuwk

eblbsuwk1#

您需要首先选择问题,然后为每个问题ID选择其选项。下面是一个示例:

function questions(){
   $qtns = array();
    $query = $this->db->get('questions_table');
    foreach($query->result_array() as $one){
        $one['choices'] = $this->questionChoices($one['id'];
        $qtns[] = $one:
    }
  return $qtns;
}

function questionChoices(int $qtnID){
    $this->db->where('o_questions_id', $qtnID);
    $query = $this->db->get('options_table');
     return $query->result_array();
}

然后,在视图中,您可以将问题显示为:

<?php foreach($qtns as $one){ ?>
  <strong><?= $one['q_id'] ?>.<?= $one['q_title'] ?></strong>
    <?php foreach ($one['choices'] as $o) { ?>
            <p><?= $o['o_title'] ?></p>
        <?php } ?>
<?php } ?>

相关问题