codeigniter 如何根据取件和返回日期进行搜索?

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

我被困了几个星期,问题是我想让用户更容易地搜索到在取车和还车日期可用的汽车名称。这个查询是不正确的,我不知道要纠正它。
我有两张表:

Cars table:
carId (prim-key)
carType,
carName
carPrice

rent table:
rentId (prim-key)
rentStart date:
rentEnd date:
rentStatus,
rentCarId (foreign key) to carId in cars table.

到目前为止我已经能够实现搜索汽车名称了。
这是我代码

//model query builder
function search($car = null , $start, $end) {
      $start= $this->db->escape($start);
      $end= $this->db->escape($end);
      $this->db->select('  carId as id,
                           rentStatus as status,
                           rentStart as start,
                           rentEnd as end,
                           carName as name,
                           carType as type,
                           carPrice as price,
                           carImage as image
                        ');

      $this->db->from('cars');
      $this->db->group_by('carName');
      $this->db->join('rent', 'carId = rentCarId', 'left');
      $this->db->like('carName', $car);
      $this->db->where('rentEnd' > $start AND 'rentStart' < $end);
      $this->db->where('rentCarId', NULL);
      
      return $this->db->get()->result_array();
   }

//controller
public function search() {
   $start= $this->input->post('start');
   $end= $this->input->post('end');
   $car= $this->input->post('car');
   $id = $this->input->post('car-id');

   $data['cars'] = $this->M_cari->search($car, $start, $end);
    
   $this->template->title('Home');
   $this->template->build($this->module.'/v_search_index', $data);
}
ukdjmx9f

ukdjmx9f1#

您使用了GROUP运算符,并且为此需要对select选择中的其余字段使用聚合函数。因此,请删除此行,并说明为什么只选择WHERE rentCarId = NULL的字段。如果您的意思是您的计算机不忙碌,那么我建议您重新考虑表的逻辑
您的查询

SELECT carId as id,
        rentStatus as status,
        rentStart as start,
        rentEnd as end,
        carName as name,
        carType as type,
        carPrice as price,
        carImage as image FROM cars
**GROUP BY carName**
JOIN rent ON carId = rentCarId
like carName $car
WHERE rentEnd > $start AND rentStart < $end
WHERE rentCarId = NULL

您的请求是错误的。您首先在关键字carId = rentCarId上联接两个表,然后要求关键字rentCarId为空。
最好的解决方案是编写一个子查询来搜索租用的汽车,并将其从所有汽车的结果中删除

SELECT carId as id,
        rentStatus as status,
        rentStart as start,
        rentEnd as end,
        carName as name,
        carType as type,
        carPrice as price,
        carImage as image FROM cars
LIKE carName $car
WHERE carId NOT IN (SELECT rentCarId FROM rent)

相关问题