Php 如何在Laravel雄辩中包含或排除where语句
对于两个不同的用户角色,我需要相同的查询。差异只存在于一个条件不好的地方 因此,对于基本用户,它将是:Php 如何在Laravel雄辩中包含或排除where语句,php,laravel,eloquent,Php,Laravel,Eloquent,对于两个不同的用户角色,我需要相同的查询。差异只存在于一个条件不好的地方 因此,对于基本用户,它将是: $chart2 = DB::connection('mysql2')->table('tv') ->select('*') ->join('epgdata_channel', 'cid', '=', 'channelid') ->where('Refe
$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}
但是我有很多查询,我只需要添加或删除whereNotin条件,使用if语句重写查询不是一个好的解决方案。试试
在TVModel.php中:
用法:
$condi = true;//or false.
$chart2 = TVModel::select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->conditionalWhereNotIn($condi, 'ChannelName', $sky)
->get();
在您的模型中添加以下内容:
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();
这个代码对我有用
$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();
$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();