我有项目表和bootstrap_themes表。
它们之间的关系是-------
项目具有一个Bootstrap主题
现在,我尝试根据该项目具有的过滤器来过滤引导主题。
$themes = BootstrapTheme::with(['item' =>function($q) use($request){
if($request->has('is_saleable')){
$q->where('is_saleable','=',$request->is_saleable);
}
if($request->has('is_disable')){
$q->where('is_disable','=',$request->is_disable);
}
}])->paginate(30);
假设我按is_disable属性过滤,则结果集如下:
{“ current_page”:1,“数据”:[{“ id”:1,“ item_id”:1,“ created_at”:“ 2017-08-17 11:24:14”,“ updated_at”:“ 2017-08 -17 11:24:14“,” item“:null}],”来自“:1,” last_page“:1,” next_page_url“:null,” path“:” http://127.0.0.1:8000/所有主题”, “per_page”:30, “prev_page_url”:空, “要”:1, “总”:1}
我的问题是,当item为null时,是否可以将分页中的BootstrapTheme计数为0。
提前致谢
您可以使用whereNull()方法检查NULL 高级where子句。
$query = Model::where('field1', '=', 1)
->whereNull('field2')
->paginate(30);
我通过使用whereExists找到了解决方案。
现在,当没有项目时,bootstraptheme将不计算在内。
$themes = BootstrapTheme::with(['item'])->whereExists(function($q) use ($request){
$q->select(DB::raw(1))->from('items')->whereRaw('bootstrap_themes.item_id = items.id');
if($request->has('is_saleable')){
$q->where('items.is_saleable','=',$request->is_saleable);
}
if($request->has('is_disable')){
$q->where('items.is_disable','=',$request->is_disable);
}
})->paginate(30);