我想从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在我的选择选项中显示,因为John和Jane的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();
}