分页与渴望加载Laravel 5.4
问题描述:
我有项目表和bootstrap_themes表。分页与渴望加载Laravel 5.4
以及它们之间的关系是-------
项目 hasOne BootstrapTheme
现在我想根据过滤器项目具有过滤bootstrapthemes。
$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}],“from”:1 “last_page”:1, “next_page_url”:NULL, “路径”: “http://127.0.0.1:8000/all-themes”, “per_page”:30, “prev_page_url”:空 “以”:1 ,“total”:1}
我的问题是,这是可以计算BootstrapTheme为0在pagina当项目为空时。
在此先感谢
答
您可以使用whereNull()方法来检查NULL advanced where clauses.
$query = Model::where('field1', '=', 1)
->whereNull('field2')
->paginate(30);
答
我用whereExists想出解决方案。
现在bootstrapthemes不会计数,当没有项目。
$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);
我想你想要计数,你可以使用 - > count(); –
我仍然得到那个项目为null的bootstraptheme。并在分页时将数据计为一行。在foreach循环中,我正在检查@if($ theme-> item)@endif以显示bootstrapTheme,但分页的函数$ themes-> total()显示1.我该如何检查? – Samvedna
你可以使用whereNull() –