请看下面的代码。这段代码是我用 Codeigniter 编写的。我需要强调的是,只有在设置了这些发布请求的情况下,条件和订单条件才起作用。否则我只是select * from student
。
Codeigniter 代码
$this->db->select('*');
$this->db->from('student');
if($this->input->post('first_name') != NULL){
$first_name = $this->input->post('first_name');
$this->db->where('first_name', $first_name);
}
if($this->input->post('last_name') != NULL){
$last_name= $this->input->post('last_name');
$this->db->where('last_name', $last_name);
}
if($this->input->post('order_by') != NULL){
$order_by= $this->input->post('order_by');
$this->db->order_by($order_by);
}
$query = $this->db->get();
Laravel 代码
我将用 laravel 做同样的事情。
$first_name = $request->input('first_name');
$last_name = $request->input('last_name');
$order_by = $request->input('$order_by');
$students = Student::orderBy($order_by)
->where('first_name',$first_name)
->where('last_name',$last_name);
->paginate(10);
我能够运行上面的代码。该代码在所有发布请求都存在时起作用。
但如果没有first_name
发布请求,我需要删除->where('first_name',$first_name)
.
如果我没有order_by
发布请求,我需要删除orderBy($order_by)
.
如何使用上面的 Laravel 代码做到这一点。
你可以使用像,
$students = Student::latest();
if (isset($request->input('order_by'))) {
$students->orderBy($order_by)
}
if (isset($request->input('first_name'))) {
$students->where('first_name',$first_name);
}
if (isset($request->input('last_name'))) {
$students->where('last_name',$last_name);
}
$students->paginate(10);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句