2014-11-01 80 views
1

如果得到了以下數據庫表: db-tableLaravel雄辯其中功能不起作用

現在我想顯示哪里哪里「inventory_warning」是更大的,則「清單」字段的行。像第二個結果,如下所示:

screenshot

在我的第一個例子,我做一個WHERE語句用雄辯的,並得到了行,但它不會產生正確的結果(它會檢索所有行)。我的第二個例子顯示了一個PHP-if語句做了檢查,這工作,但會當表中包含更多的數據非常低效..

縮短代碼:

<?php $products = Product::where('inventory_warning', '>', 'inventory')->get();?> 
    <tr> 
     <th colspan="3">First results:</th> 
    </tr> 
    @foreach($products as $product) 
     <tr> 
      <td># {{ $product->id }} - {{$product->item->name}}</td> 
      <td>{{ $product->inventory }}</td> 
      <td>{{ $product->inventory_warning }}</td> 
     </tr> 
    @endforeach 

<?php $products = Product::all();?> 
    <tr> 
     <th colspan="3">Second results:</th> 
    </tr> 
    @foreach($products as $product) 
     @if($product->inventory_warning > $product->inventory) 
      <tr> 
       <td># {{ $product->id }} - {{$product->item->name}}</td> 
       <td>{{ $product->inventory }}</td> 
       <td>{{ $product->inventory_warning }}</td> 
      </tr> 
     @endif 
    @endforeach 

這到底是怎麼回事?這是一個可能的雄辯錯誤還是我做錯了什麼?

回答

4

據我所知,where函數不支持比較兩個數據庫字段。 您必須使用whereRaw

Product::whereRaw('inventory_warning > inventory')->get(); 
+0

是的,謝謝!這似乎起作用了,快速瀏覽Eloquent的來源,證實where函數確實不支持字段比較。 (本來可以期望的).. 函數聲明: public function where($ column,$ operator = null,$ value = null,$ boolean ='and') – EvdTempel 2014-11-01 11:22:38