簡體   English   中英

如何預測另一個表CodeIgniter中不存在的數據

[英]How to foreach data that not exist in another table CodeIgniter

我想從一個表列中獲取與另一個表相關的數據,使用CI中的foreach方法,所以左邊船員表, 右邊contrib表(用'/'分隔):

+====+======+===+====+=========+
| id | name | / | id | crew_id |
+====+======+===+====+=========+
|  1 | John | / |  1 |       1 |
+----+------+---+----+---------+
|  2 | Jane | / |  2 |       1 |
+----+------+---+----+---------+
|  3 | Jody | / |  3 |       2 |
+----+------+---+----+---------+

在我試過的模型任務模型上:

public function list_contrib(){
    $this->db->select('contrib.*, crew.name');
    $this->db->from('contrib');
    $this->db->join('crew', 'contrib.crew_id = crew.id' 'inner);
    $query = $this->db->get();
    return $query->result();
}

public function crew_list(){
    $this->db->select('*');
    $this->db->from('crew');
    $query = $this->db->get();
    return $query->result();
}

在控制器上:

 public function add_task(){

    $this->load->model('taskmodel');

    $data['crews']   = $this->taskmodel->crew_list();
    $data['contrib'] = $this->taskmodel->list_contrib();

    $this->load->view('add_task', $data);
}

在視圖上:

<?php foreach($contrib as $cont): ?>
    <select>
    <?php foreach($crews as $crew):
          if($crew->id != $cont->crew_id ) { ?>
      <option value="<?php $crew->id ?>"><?php echo $crew->name ?></option>
    <?php } endforeach; ?>
    </select>             
<?php endforeach; ?>

它在我的選擇選項中包含Jane 我希望只有Jody在我的選擇選項中顯示,因為JohnJane的id存在於contrib表中。 抱歉英文不好。 有任何想法嗎?

因為你使用內連接。 嘗試使用左或右連接

public function list_contrib(){
    $this->db->select('contrib.*, crew.name');
    $this->db->from('contrib');
    $this->db->join('crew', 'contrib.crew_id = crew.id', 'left');
    $query = $this->db->get();
    return $query->result();
}

暫無
暫無

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

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