我的Codeigniter中有2个模型,1个获得所有房间,第二个模型是在所选日期范围内获得预订的房间。
在我看来,我可以用foreach列出所有房间,当我为预订的房间插入另一个foreach以红色显示时,我得到一个结果但是,我看到重复的结果
我的模特:
public function rooms(){
$result = $this->db->select('*')
->from('rooms')
->group_by('room_id')
->get()
->result();
return $result;
}
public function check_room_availability($start, $end){
$this->db->select('*');
$this->db->from('room_actions as ra', 'rooms as r');
$this->db->join('rooms as r', 'r.room_id = re.room_id', 'LEFT');
$this->db->where('ra.days >=', $start);
$this->db->where('ra.days <=', $end);
$this->db->group_by('ra.room_id');
$query = $this->db->get()->result();
return $query;
}
我的观点:
<?php foreach($all_rooms as $room) {
foreach($booked_ones as $booked) {?>
<div class="<?php
if($booked->room_id == $room->room_id){
echo 'room_box red';}
else{
echo 'room_box green';}?>">
<?php echo $room->room_id; ?>
</div>
<?php } ?>
<?php } ?>
如果你能帮助我,我会很感激。谢谢。
正如您在下图所示,如果我在所选日期预订了2间客房,我的房间将重复。如果我预订了3个房间,那么它就变成了X 3。
试试这个,希望它会对你有所帮助。
如果rooms
表有一个独特的room_id
然后不需要使用group_by()
public function rooms(){
$result = $this->db->select('*')
->from('rooms')
->get()
->result();
return $result;
}
这里不需要join()
public function check_room_availability($start, $end){
$booked_rooms = array();
$this->db->select('room_id');
$this->db->from('room_actions as ra');
$this->db->where('ra.days >=', $start);
$this->db->where('ra.days <=', $end);
$query = $this->db->get()->result();
if(isset($query) && count($query) > 0){
foreach($query as $row){
if(!in_array($row->room_id, $booked_rooms)){
array_push($booked_rooms, $row->room_id);
}
}
}
return $booked_rooms;
}
现在您有一个简单的预订房间ID数组。在视图中只使用一个forach()
循环执行此操作
foreach($all_rooms as $room) {
if(in_array($room->id, $booked_rooms)){
//Room is booked
}
}
试试这个,
public function check_room_availability($start, $end) {
$this->db->select('r.room_id as room_id,ra.room_id as booked_room_id');
$this->db->from('rooms as r');
$this->db->join('room_actions as ra', 'r.room_id = ra.room_id', 'LEFT');
$this->db->where('ra.days >=', $start);
$this->db->where('ra.days <=', $end);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return array();
}
}
要么
public function check_room_availability($start, $end) {
$this->db->select('*,(select room_id from room_actions as ra where ra.room_id = r.room_id and ra.days >=' . $start . ' and ra.days <=' . $end . ') as booked_room_id');
$this->db->from('rooms as r');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return array();
}
}
为了更好的结果,请分享您的表或您的预期输出,根据我可以更新我的查询