简体   繁体   English

Laravel Eloquent 查询过滤器不工作

[英]Laravel Eloquent Query Filter not working

Hi I am new to programming.嗨,我是编程新手。 My Application have a filter function.我的应用程序有一个过滤器 function。 where a user select two dates on front end.其中用户 select 在前端有两个日期。 In eloquent query it should return records which are published by user itself or the record published by other user set to public and also filter records according to the dates given.在 eloquent 查询中,它应该返回用户自己发布的记录或其他用户发布的记录设置为公共,并根据给定的日期过滤记录。 Here is code:这是代码:

$maps = Mapdata::where('userid', Auth::user()->id)->ORwhere('public', 1)->whereBetween('from', array($request->from, $request->to))->ORwhereBetween('to', array($request->from, $request->to))->orderBy('id', 'DESC')->get();

I have noticed that the date and time filter is not capturing all the relevant records.我注意到日期和时间过滤器没有捕获所有相关记录。 For example: a filter from 22/5/21 to 23/5/21 should return 3 records.例如:从 22/5/21 到 23/5/21 的过滤器应该返回 3 条记录。 Expected Result but it showing Actual Result .预期结果,但它显示实际结果 Also One of the records displayed is not even public record.此外,显示的记录之一甚至不是公共记录。 Please guide me how to do that请指导我如何做到这一点

I think you need to combine where between like below我认为您需要结合下面的位置

$maps = Mapdata::where('userid', Auth::user()->id)
                    ->ORwhere('public', 1)->where(function($query){
                    $query->whereBetween('from', array($request->from, $request->to))
                    $query->ORwhereBetween('to', array($request->from, $request->to))
                    })->orderBy('id', 'DESC')->get();

Updated更新

$maps = Mapdata::where('userid', Auth::user()->id)
                    ->ORwhere('public', 1)->where(function($query)use($request){
                    $query->whereBetween('from', array($request->from, $request->to))
                    $query->ORwhereBetween('to', array($request->from, $request->to))
                    })->orderBy('id', 'DESC')->get();

You need to wrap conditions in additional where to add ( to query, so it should be probably something like this:您需要将条件包装在要添加的附加位置(以进行查询,因此它应该可能是这样的:

$maps = Mapdata::where(function($q) {
   $q->where('userid', Auth::user()->id)->orWhere('public', 1); 
})->where(function($q) use ($request) {
   $q->whereBetween('from', array($request->from, $request->to))->orWhereBetween('to', array($request->from, $request->to));
})->orderBy('id', 'DESC')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM