2017-08-17 118 views
0

我有項目表和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當項目爲空時。

在此先感謝

+0

我想你想要計數,你可以使用 - > count(); –

+0

我仍然得到那個項目爲null的bootstraptheme。並在分頁時將數據計爲一行。在foreach循環中,我正在檢查@if($ theme-> item)@endif以顯示bootstrapTheme,但分頁的函數$ themes-> total()顯示1.我該如何檢查? – Samvedna

+0

你可以使用whereNull() –

回答

0

您可以使用whereNull()方法來檢查NULL advanced where clauses.

$query = Model::where('field1', '=', 1) 
->whereNull('field2') 
->paginate(30); 
0

我用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);