2017-08-29 71 views
0

我需要兩個不同的用戶角色相同的查詢。區別只在於一個whereNotIn的情況。如何包含或排除在Laravel中的語句雄辯

因此,對於基本的用戶將是:

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

而對於高級:

$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} 

但我有很多的查詢,我只需要添加或刪除這裏的諾丁條件和重寫查詢(使用如果政治家噸)不是一個很好的解決方案。

回答

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(); 
0

內部模型補充一點:

public function scopeBasicUser($query,$channel){ 
return $query->whereNotIn('ChannelName', $channel); 
} 

和控制器:

$query = DB::connection('mysql2')->table('tv') 
     ->select('*') 
     ->join('epgdata_channel', 'cid', '=', 'channelid') 
      ->where('ReferenceDescription', $campaign->spotid); 
if($user->userRole == "Basic") 
    $query = $query->basicUser($channel); 
return $query->get();