在Laravel中选择两个值之间的查询

时间:2014-11-03 16:08:36

标签: php mysql laravel-4 query-builder

我尝试使用Laravel和查询构建器来提取价格介于1和最高产品价格之间的产品的数量。

我在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中我没有指定我们必须搜索的范围:

$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

4 个答案:

答案 0 :(得分:1)

whereBetween要求values数组的第二个元素是静态值或变量,而不是表中的列。您可以使用两个whereRaw语句(没有whereBetweenRaw等效语句),当它们一起使用时,将创建和and条件,即:

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

DB::raw在这种情况下无法工作,并且两个常规where条款也无法正常工作。

答案 1 :(得分:0)

这很奇怪,据我所知,您正确使用whereBetween()。你可以尝试两件事:

  • 在数组中取消引用products.price
  • 只需使用两个where子句(&gt; =&amp;&amp;&lt; =)

希望这有帮助。

答案 2 :(得分:0)

有可能将products.price转义为字符串。试试DB::raw('products.price')

答案 3 :(得分:0)

whereBetween()只接受整数,也许你的变量是字符串。