2014-11-03 35 views
0

我試圖用Laravel和查詢構建器來提高產品價格在1和最大產品價格之間的數量。在Laravel中的兩個值之間選擇查詢

我試圖與此查詢在phpMyAdmin,它返回一個結果:

SELECT product_id ,  count(user_id) , sum(monies) 
    FROM products, prices 
    WHERE monies 
    BETWEEN '20' 
    AND products.price 

    AND products.id = 101 
    GROUP BY (product_id); 

但在PHP我coudn't指定上,我們必須搜索範圍:

$data = Product::join('prices', 'prices.product_id', '=', 'products.id') 
       ->select(DB::raw('count(user_id) as nombre'),DB::raw('sum(monies) as sum')) 
       ->where('prices.project_id', '=', '101') 
       ->whereBetween('monies', array(1, 'products.price')) 
       ->groupBy('prices.product_id') 
       ->get(); 

但我總是得到一個空的結果,當我改變whereBetween('monies', array(1, 'products.price'))whereBetween('monies', array(1, 1000))它返回一個結果。

如何使用whereBetween

回答

1

whereBetween要求values數組的第二個元素是靜態值或變量,但不是表中的列。您可以使用兩個whereRaw語句(沒有whereBetweenRaw當量),其中,一起使用時,將創建和and條件,即:

->whereRaw('monies >= 1')->whereRaw('monies <= products.price') 

DB::raw不會在這種情況下工作,兩個常規where條款拿下也不行。

0

這很奇怪,你正在使用whereBetween()據我所知。有兩兩件事你可以嘗試:

  • 引文結束products.price數組中
  • 只需使用兩個where子句(> = & & < =)

希望這有助於。

+0

該問題與whereBetween子句中與where'Between之間使用'products.price'相關的地方無關。 – 2014-11-03 16:46:29

0

機會是products.price被作爲字符串轉義。嘗試DB::raw('products.price')

+0

它不能與'DB :: raw('products.price')一起使用' – 2014-11-03 16:47:32

+0

查看它通過執行'toSql()'而不是'get()'生成的查詢。 – ceejayoz 2014-11-03 17:58:59

0

whereBetween()只接受整數可能你的變量是字符串。