我在 codeigniter 中有一个预订模块,我限制用户每天只能预订 2 小时的会所。我目前正在 codeigniter 中创建验证以限制他们的预订。我所做的是选择所有预订,并将它们按具有相同日期的行分组,以便适本地限制它们。问题是我创建的模型只返回 1 行,而不是所有结果。这意味着我的计数器只改变了一行,我希望所有行都应该影响计数器。 下面是我的数据库表:
基本上,第二行不应插入到数据库中,因为用户“20130123”已经用完了他当天的最大预留时间,即两个小时。我在下面提供了验证检查,检查用户是否用完了两个小时的预订,我的逻辑是我只是用预订开始减去预订结束。使用上表作为示例并进行解释,我的问题是在我的模型中,计数器的值变为“2”,因为它只读取第一行 (8 - 6 = 2),而不是“3”(第一行的结果是 2,然后加上第二行的结果是 1 : [(8-6) + (9-8)])
总而言之,我的问题在于计数器的值,因为它仅在查询读取的第一行添加。
这是我的代码。
型号:
function check_twohours_clubhouse()
{
$query = $this->db->select('*')->from('clubhouse_reservation')->where('username', $this->session->userdata('username'))->group_by('reservation_date')->having('count(reservation_date) > 1')->get();
$result = $query->result();
if($query->num_rows() > 0)
{
$ctr = '0';
foreach($result as $row)
{
$totalhour = $row->reservation_end - $row->reservation_start; // subtract reservation start to reservation end to get the number of hours
$ctr = $ctr + $totalhour;
}
$ctr = $ctr + ($this->input->post('reserveend') - $this->input->post('reservestart')); // add the selected "add reservation" hours to the counter
if($ctr > 2) // counter > 2 hours limit
{
return FALSE;
}
else
{
return TRUE;
}
}
else
{
return TRUE;
}
}
Controller :
function create_reservation_clubhouse()
{
$this->form_validation->set_error_delimiters('<div class="error">','</div>');
$this->form_validation->set_rules('datepick', 'Date', 'required|no_olddate');
$this->form_validation->set_rules('reservestart', 'Reservation Start', 'required|hourselection|unique_reserve_clubhouse|max_twohours');
if ($this->form_validation->run() == FALSE)
{
$this->template->load('user_template', 'view_userreservation_addclubhouse');
}
else
{
if($this->model_reservation_user->check_twohours_courtone())
{
if($query = $this->model_reservation_user->create_reservation_clubhouse())
{
$this->session->set_flashdata('reservefeedback', 'You have successfully reserved a date for the Clubhouse. Please wait for the administrators to accept your reservation.');
redirect('user_reservation/clubhouse');
}
}
else
{
$this->session->set_flashdata('reservefail', 'You cannot reserve more than two hours of Clubhouse per day.');
redirect('user_reservation/clubhouse');
}
}
}
最佳答案
您可以使用 time_to_sec() 在 sql 中计算所有这些和 timediff()功能:
select reservation_date, sum(time_to_sec(timediff(reserveend, reservestart)) / 3600 as reserved_hours
from clubhouse_reservation
where username =...
group by reservation_date
having count(*)>1 --although it is not clear to me why you have this restriction
上述查询将针对每个预订日期的给定用户汇总会所预订的小时数(3600 = 一小时内的秒数)。
在您的 php 代码中,您只需要检查结果集中的 reserved_hours
是否为 >2。
我不是真正的 CI 专家,因此我真的不知道如何将上面的 sql 转换为 CI。但恐怕你必须使用原始 sql,因为它计算时间的方式。
关于php - Codeigniter Group 通过仅返回第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342683/