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()])));
       });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作