2017-08-01 127 views
0

我有一個查詢如下:laravel數據庫查詢工作不正常

$this->_data['news'] = PageContent::orderBy('created_at', 'desc')->where('category_id', 3)->where('status', 1)->first(); 

而且在我index.blade.php文件,數據顯示在這樣的方式:

@if(count($news) > 0) 
    <div class="post_list_content_unit col-sm-6"> 
     <div class="feature-image"> 
      <a href="{{URL::to('/')}}/about-us/news-event" class="entry-thumbnail"> 
       <img width="370" height="260" 
        src="{{URL::to('Uploads/pageContents/'.$news->image)}}" 
        alt="{{$news->title}}"> 
      </a> 
     </div> 
     <div class="post-list-content"> 
      <div class="post_list_inner_content_unit"> 
       <h3 class="post_list_title"> 
        <a href="{{URL::to('/')}}/about-us/news-event" 
         rel="bookmark">{{$news->title}}</a> 
       </h3> 
       <div class="post_list_item_excerpt"> 
        {!! str_limit($news->description, 300) !!} 
       </div> 
      </div> 
     </div> 
    </div> 
@else 
    <div></div> 
@endif 

但是相反只顯示狀態= 1的記錄,它也顯示狀態值爲0的數據。

查詢有問題嗎?

回答

-1

你應該試試這個:

$this->_data['news'] = PageContent::orderBy('created_at', 'desc') 
      ->where(function($query) { 
       $query->where('category_id', 3) 
       $query->where('status', 1); 
      }) 
      ->first(); 

希望這對你的工作!

+0

但我不想顯示被禁用的記錄...我猜這個查詢不適用於此。 – Azima

+0

@Azima請檢查我的更新回答 –

+0

這將獲取記錄0狀態值太...不工作 – Azima

2

你可以傳遞一個數組到where方法:

$this->_data['news'] = PageContent::orderBy('created_at', 'desc') 
->where(array('category_id'=>3,'status'=>1)) 
->first(); 
+0

事實上,如果您不知道過濾器的確切數量,我覺得這種方式有點靈活 –

0

你可以通過數組中做兩個方面的where子句:

$this->_data['news'] = DB::table('PageContent') 
    ->orderBy('created_at', 'desc') 
    ->where([ 
     ['category_id', '=', '3'], 
     ['status', '=', '1'], 
     ])->first(); 

或者通過

$this->_data['news'] = PageContent::orderBy('created_at', 'desc') 
    ->where([ 
     ['category_id', '=', '3'], 
     ['status', '=', '1'], 
     ])->first();