dppcyt6157 2015-12-07 13:44
浏览 691

如何自定义Laravel whereBetween子句使上限无限制?

I have been working on laravel using eloquent query builders. I have a situation in which I am filtering records based on search queries. I have an integer field, for which I want to filter data in ranges. User can select any of available ranges for example; 0-15, 15-30 and 30 and above. For this purpose I found Query-builders whereBetween() clause very helping. But It becomes difficult for me for last option when I want to select for 30 and above. I would really appreciate if someone could help me with some trick make this query

->whereBetween('time_taken', [$lower-limit,$uper_limt])

working for all cases. I don't want to write an additional line for this case, at which I can use simple where clause

->where('time_taken','>=',$uper_limt).

  • 写回答

2条回答 默认 最新

  • dongming8867 2015-12-07 16:18
    关注

    The practical solution here is to just choose the appropriate SQL condition (I'm using a ternary operator here to keep it more compact):

    $query = App\Operation::query();
    
    (empty($upper_limit)) ? $query->where('time_taken','>=', $lower_limit)
                          : $query->whereBetween('time_taken', [$lower_limit, $upper_limit]);
    
    $results = $query->get();
    

    Sure it would be nice to have just one line:

    $results = App\Operation::whereBetween('time_taken', [$lower_limit, $upper_limit])->get();
    

    But that's not possible in this case, not unless you want to extend the Laravel Query Builder and modify the way it handles empty parameters in the range passed as the value.


    Writing clean and concise code is something we all strive to achieve, but one line solutions are not always possible. So my advice is to stop fixating (something I sometimes do myself) on things like this, because in some cases it's a lost cause that just ends up wasting time.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分