PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 4, 2022

[FIXED] How to query using whereBetween() from selected DB::raw() value

 February 04, 2022     laravel, php, sql     No comments   

Issue

I have a query result with the selected DB raw result and I need to add another where between clause to that query with the selected DB raw result. my query is

$products = Product::leftJoin('product_reviews', 'product_reviews.product_id', '=', 'products.id')
                ->select(
                    'products.*',
                    DB::raw("IF(SUM(product_reviews.star_rating) != 0, SUM(product_reviews.star_rating) / COUNT(product_reviews.id), 0) AS rate")
                )
                ->get();

I need to add ->whereBetween('rate', [4, 5]) like this to my query. How can I do that?


Solution

You must use ->havingBetween('rate', [4, 5])

$products = Product::leftJoin('product_reviews', 'product_reviews.product_id', '=', 'products.id')
    ->select(
        'products.id',
        DB::raw("IF(SUM(product_reviews.star_rating) != 0, SUM(product_reviews.star_rating) / COUNT(product_reviews.id), 0) AS rate")
    )
    ->groupBy('products.id')
    ->havingBetween('rate', [4, 5])
    ->get();

Online Laravel query builder test



Answered By - Slava Rozhnev
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing