如何在Laravel Eloquent中包含或排除where语句

时间:2017-08-29 09:16:33

标签: php laravel eloquent

我需要对两个不同的用户角色进行相同的查询。差异仅在一个whereNotIn条件下。

因此,对于Basic用户来说,它将是:

$chart2 = DB::connection('mysql2')->table('tv')
                    ->select('*')
                    ->join('epgdata_channel', 'cid', '=', 'channelid')
                    ->where('ReferenceDescription', $campaign->spotid)
                    ->whereNotIn('ChannelName', $sky)
                    ->get();

对于Premium:

$chart2 = DB::connection('mysql2')->table('tv')
                    ->select('*')
                    ->join('epgdata_channel', 'cid', '=', 'channelid')
                    ->where('ReferenceDescription', $campaign->spotid)
                    ->get();

我知道我可以用简单的if语句来做到这一点:

    if($user->userRole == "Basic"){
    //first $chart2
}
    else{
    //second $chart2}

但我有很多查询,我只需要添加或删除whereNotin条件并重写查询(使用if语句)不是一个很好的解决方案。

3 个答案:

答案 0 :(得分:1)

尝试scope

TVModel.php

public function scopeConditionalWhereNotIn($query, $doesUse, $col, $val) {
    if($doesUse)
        $query->whereNotIn($col, $val);
}

用法:

$condi = true;//or false.
$chart2 = TVModel::select('*')
                ->join('epgdata_channel', 'cid', '=', 'channelid')
                ->where('ReferenceDescription', $campaign->spotid)
                ->conditionalWhereNotIn($condi, 'ChannelName', $sky)
                ->get();

答案 1 :(得分:0)

在模型中添加以下内容:

 SELECT RIGHT('0'+CAST(Z AS VARCHAR(2)),2)+'-'+RIGHT('0'+CAST(Z+1 AS VARCHAR(2)),2) AS HOUR_GR, COALESCE(RC,0) AS RC
 FROM (
     SELECT -1+ROW_NUMBER() OVER (ORDER BY A1.Y) AS Z 
     FROM (SELECT 1 AS Y UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) A1
            CROSS JOIN (SELECT 1 AS Y UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5) A2
    ) B
 LEFT JOIN  (SELECT X, CAST(X  AS VARCHAR(2)) +'-'+CAST(X +1 AS VARCHAR(2)) AS HOUR_GROUP, COUNT(*) AS RC
             FROM (SELECT  DATEPART(hh,ORD_DATE) X FROM ORD) A
             GROUP BY X
            ) C ON B.Z= C.X
 WHERE B.Z<24

并在您的控制器中:

HOUR_GR RC
00-01   4
01-02   1
02-03   0
03-04   0
04-05   0
05-06   0
06-07   0
07-08   0
08-09   0
09-10   0
10-11   1
11-12   0
12-13   0
13-14   0
14-15   0
15-16   1
16-17   0
17-18   0
18-19   0
19-20   0
20-21   1
21-22   0
22-23   0
23-24   0

答案 2 :(得分:0)

$userRole = $user->userRole;
$chart2 = DB::connection('mysql2')->table('tv')
            ->select('*')
            ->join('epgdata_channel', 'cid', '=', 'channelid')
            ->where('ReferenceDescription', $campaign->spotid)
            ->where(function ($query) use ($userRole){
                if($userRole == "Basic"){
                    $query->whereNotIn('ChannelName', $sky)
                }
            })
            ->get();

此代码对我有用。