0

I'm trying to extrat the number of a product which prices between 1 and the max product price using Laravel and query builder.

I tried with this query in phpmyadmin and it returns a result:

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

But in PHP I coudn't specify the range on which we have to search :

$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();

But I always get an empty result and when I change whereBetween('monies', array(1, 'products.price')) with whereBetween('monies', array(1, 1000)) it returns a result.

How can I use the whereBetween?

4 Answers 4

2

whereBetween requires the second element of the values array to be either a static value or a variable, but not a column from your table. You can use two whereRaw statements (there is no whereBetweenRaw equivalent), which, when used together, will create and and condition, i.e.:

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

DB::raw won't work in this scenario, and two regular where clauses won't work either.

Sign up to request clarification or add additional context in comments.

Comments

0

That's weird, you're using whereBetween() correctly as far as I know. Two things you could try:

  • Unquote products.price in the array
  • Simply use two where clauses (>= && <=)

Hope this helps.

1 Comment

the problem is not related to the whereBetween it's related to the using of 'products.price' in the whereBetween clause.
0

Chances are products.price is being escaped as a string. Try DB::raw('products.price').

2 Comments

it doesn't work also with DB::raw('products.price')
Take a look at the query it's generating by doing toSql() instead of get().
0

whereBetween() just accept integer maybe your variable is string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.