在laravel包含之间的哪个位置?

时间:2016-06-02 06:42:56

标签: php mysql laravel laravel-5

在我的数据库中有4名学生:

1st Student's created_at = 2016-05-12 02:23:51

2nd Student's created_at = 2016-05-27 07:37:45

3rd Student's created_at = 2016-05-29 07:40:29

4th Student's created_at = 2016-05-29 07:50:05

为什么我的代码只返回第一个学生?

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                             ->whereBetween('created_at', 
                              [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                               Carbon::createFromDate(2016, 5, 27)->toDateString()])

应该退回第一和第二名学生。 “to”部分是否包含在WhereBetween或我的代码中有什么问题?

我需要你的帮助。提前谢谢!

4 个答案:

答案 0 :(得分:31)

对于那些最终到这里并希望得到问题答案的人(如果它已更新......" Laravel包含哪些内容?"):

答案 1 :(得分:4)

Laravel搜索between,这意味着它会获得2016-05-12 00:00:002016-05-27 00:00:00之间的所有行。您的第二个用户是在2016-05-27 07:37:45创建的,这超出了范围,因此Laravel无法获取它。

使用此功能并尝试以下方法:

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                             ->whereBetween('created_at', 
                              [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                               Carbon::createFromDate(2016, 5, 28)->toDateString()])

希望这有效!

答案 2 :(得分:2)

您需要格式化created_atY-m-d格式。 请参阅更改:

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                                 ->whereBetween(DB::raw('date(created_at)'), 
                                  [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                                   Carbon::createFromDate(2016, 5, 27)->toDateString()])

答案 3 :(得分:0)

快速解决方案

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                             ->whereBetween(DB::raw('date(created_at)'), 
                              [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                               Carbon::createFromDate(2016, 5, 27)->toDateString()])