简体   繁体   中英

Convert MYSQL query into Laravel 5 query

Okay so i have got my project working however a lot of my database are kind of raw queries and i want to do it in the laravel 5 way.

So far I have managed to do some simple ones in laravel 5 easily however I am struggling to replicate this query in laravel:

$ave=DB::select("SELECT `question`.`questionID`,
COUNT(`reviewmeta`.`id`) as count,  `reviewmeta`.`answer` 
FROM `question` 
JOIN `reviewmeta` 
ON (`question`.`questionID` = `reviewmeta`.`questionID`) 
WHERE `question`.`watchID`='".$hwid."' 
AND  `question`.`type`='FFT' 
GROUP BY `reviewmeta`.`answer` "); 

For an example this is how I converted one of my raw queries:

Laravel 5 way

public static function getWatchListInfo($serviceIDS){
    $services = DB::table('services')
                ->distinct()
                ->leftJoin('reviews','services.serviceID','=','reviews.serviceID')
                ->join('service_categories','services.type','=','service_categories.categoryID')
                ->select('services.id','services.name','services.review_count_approved','reviews.escalate','services.average_rating','service_categories.name as catName')
                ->whereIn('services.serviceID',$serviceIDS);
    return $services;
}

You just need to add ->count() like this :

->whereIn('services.serviceID',$serviceIDS)->count()

DB::table('questions')
->select(['reviewmeta.answer', DB::raw('COUNT(reviewmeta.id) as count')])
->leftJoin('reviewmeta', 'question.questionID', '=' ,'eviewmeta.questionID')
->where('question.watchID', $hwid)
->where('question.type', 'FFT')
->groupBy('reviewmeta.answer');

Somebody correct me if I'm wrong, it's been some time since I've done laravel related queries.

Almost the same with @Andrew's answer, just you can use select function like this.

$ave=DB::table('questions')
->select('question.questionID', DB::raw('COUNT(reviewmeta.id) as count'),'reviewmeta.answer')
->join('reviewmeta', 'question.questionID', '=' ,'reviewmeta.questionID')
->where('question.watchID', $hwid)
->where('question.type', 'FFT')
->groupBy('reviewmeta.answer');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM