一次写多个laravel查询

时间:2017-06-10 13:24:55

标签: laravel

我是laravel的新手,我只是想知道是否有任何方法可以有效地重写此代码?

$answer1 = SurveyAnswer::where('answer_1','=','1')->get()->count();
$answer2 = SurveyAnswer::where('answer_1','=','2')->get()->count();
$answer3 = SurveyAnswer::where('answer_1','=','3')->get()->count();
$answer4 = SurveyAnswer::where('answer_1','=','4')->get()->count();
$answer5 = SurveyAnswer::where('answer_1','=','5')->get()->count();

3 个答案:

答案 0 :(得分:1)

首先获取数据:

#include "opencv2/core/core.hpp"
#import "opencv2/highgui/cap_ios.h"

UIImage* MatToUIImage(const cv::Mat& image);
void UIImageToMat(const UIImage* image,
                     cv::Mat& m, bool alphaExist = false);

然后使用加载的集合计算答案:

$answers = SurveyAnswer::whereIn('answer_1', [1, 2, 3, 4, 5])->get();

此代码只生成一个数据库查询,而不是五个。

答案 1 :(得分:0)

试试这个:

$matches = [1,2,3,4,5];

$answer = SurveyAnswer::whereId('answer_1', $matches)->groupBy('answer_1')->get();

答案 2 :(得分:0)

您可以使用带有case表达式的agregate函数轻松完成此操作,因为mysql不支持本机透视函数 以下是一个示例,并尝试根据您的要求重写并直接对数据库进行处理,如果有效,则可以将其与laravel raw sql一起使用。

 select id,
 sum(case when value = 1 then 1 else 0 end) ANSWER1_COUNT,
 sum(case when value = 2 then 1 else 0 end) ANSWER2_COUNT
from survey
group by answer