Laravel orwhere和whereBetween查询不能一起工作

时间:2018-04-04 04:15:49

标签: php database laravel laravel-5.4

我有一种情况来过滤数据库中的用户,以便从具有特定ID的表的两列过滤,并且应该使用一系列日期进行过滤。

我的代码如下所示。

$fetchSelectedUser=Wallet_Transaction::select('wallet__transactions.from as FromUser','wallet__transactions.type','wallet__transactions.date','wallet__transactions.amount','wallet__transactions.balance_after',
               'wallet__transactions.type','wallet__transactions.description','wallet__transactions.to as ToUser','users.name as FromName',DB::raw('(select name from users where users.id = ToUser) as toName'))
               ->join('users','users.id','=','wallet__transactions.from')
               ->where('wallet__transactions.from','=',$user_id)->orWhere('wallet__transactions.to','=',$user_id)
               ->whereBetween('wallet__transactions.db_date',[$fromDate,$toDate])->get();

我试过的是一个静态日期,但是没有用。我还独立删除了orWherewhereBetween。那很有效。但它不会合作。

1 个答案:

答案 0 :(得分:2)

使用where()封锁对您的conditional查询进行分组:

$fetchSelectedUser=Wallet_Transaction::select('wallet__transactions.from as FromUser','wallet__transactions.type','wallet__transactions.date','wallet__transactions.amount','wallet__transactions.balance_after',
           'wallet__transactions.type','wallet__transactions.description','wallet__transactions.to as ToUser','users.name as FromName',DB::raw('(select name from users where users.id = ToUser) as toName'))
           ->join('users','users.id','=','wallet__transactions.from')
           ->where(function($q) use ($user_id){
                $q->where('wallet__transactions.from','=',$user_id)->orWhere('wallet__transactions.to','=',$user_id);
           })->whereBetween('wallet__transactions.db_date',[$fromDate,$toDate])->get();