dovhpmnm31216 2016-10-19 14:51
浏览 156
已采纳

Laravel数据库查询返回错误的值

So in my database I have table called "records", which contains approximately 1k entries. This table contains such fields as "id", "title", "date_finished", "category_id", "user_id" and some more.

"date_finished" by default is 0000-00-00 00:00:00, but user can change it to current timestamp. And so, in this table approximately the half has default date_finished and another half has custom.

In my HTML I have input with type="month" which sends year and month to the controller in format like "2016-10".

And I need to get only those entries that have either default date_finished property or date_finished with month and year received from input.

In the beginning of my controller I wrote that

$record_query =  DB::table('records');

Then, I need some additional options to be used, so I have two arrays — $users and $categories containing some ids. Then, I do

$record_query = $record_query
       ->where(function($q) use ($users){ $q->whereIn('records.user_id', $users); })
       ->orWhere(function($q) use ($categories){                
            $q->whereIn('records.category_id', $categories);
        });

And after that I have about 700 entries left from 1k.

And here is the part where the problem is.

To get only those entries that meet the requirements mentioned above, I do

$month = Input::get('month');
$record_query = $record_query->where(function($w) use($month){
      $w->where('records.date_finished','0000-00-00 00:00:00')
      ->orWhere(function($q) use ($month){                
            $q->where('records.date_finished','!=','0000-00-00 00:00:00')
           ->whereBetween('records.date_finished',array(date('Y-m-d', strtotime($month)), date('Y-m-d', strtotime($month.'+1 month'))));
       });
});

And after this modification I get some 300 entries that do not meet those requirements. The array I get the end contains some random entries with default date_finished and custom date_finished that has nothing common with one I send from input.

When I run the same query directly in SQL, I get correct results.

Where am I wrong?

  • 写回答

1条回答 默认 最新

  • dqoag62688 2016-10-19 15:27
    关注

    I think you need something like

    $date = Carbon::createFromDate(null, $month, null);
    
    $record_query = $record_query->where(function($w) use($date){
        $w->where('records.date_finished','0000-00-00 00:00:00')
            ->orWhere(function($q) use ($date){                
                $q->whereBetween('records.date_finished', [$date->toDateString(), $date->addMonth()->toDateString()])));
       });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,