Laravel:连接多个选择语句

时间:2019-01-02 06:33:24

标签: mysql laravel

我有一个调查应用程序。 每个SurveyResponse具有多个QuestionResponses。 出于报告目的,我想基于对属于同一QuestionResponses的其他QuestionResponses的回答值来过滤SurveyResponse-例如。给我所有为Male问题选择Gender的人的问题答案。

以下示例SQL查询正在运行,但是我正努力在Laravel中复制它:

SELECT * 
FROM ( SELECT * 
FROM ( SELECT * 
       FROM question_responses ) AS A

JOIN ( SELECT survey_response_id AS JOIN_A
       FROM question_responses
       WHERE (question_short_name = 'Gender') AND (value = 'Male')) AS B
ON A.survey_response_id= JOIN_A) AS C

JOIN ( SELECT survey_response_id AS JOIN_B
       FROM question_responses
       WHERE (question_short_name = 'Age') AND (value = '45 to 54')) AS D
ON C.survey_response_id=JOIN_B

我该如何使用Eloquent或Laravel的查询生成器?

2 个答案:

答案 0 :(得分:0)

您可以使用雄辩的关系,但是如果您想使用这种特定类型的查询,则可以在laravel中使用DB类。

use Illuminate\Support\Facades\DB;

$data = DB::select(DB::raw('SELECT * 
FROM ( SELECT * 
FROM ( SELECT * 
       FROM question_responses ) AS A

JOIN ( SELECT survey_response_id AS JOIN_A
       FROM question_responses
       WHERE (question_short_name = 'Gender') AND (value = 'Male')) AS B
ON A.survey_response_id= JOIN_A.your_id) AS C

JOIN ( SELECT survey_response_id AS JOIN_B
       FROM question_responses
       WHERE (question_short_name = 'Age') AND (value = '45 to 54')) AS D
ON C.survey_response_id=JOIN_B.your_id'))

获得响应后,您可以通过$ data [0] ['key']检索数据以使用'->'或将其收集起来,然后可以使用Collection类。

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Collection;

$tempData = Collection::make(DB::select(DB::raw('select query'));
($tempData[0])->key;

答案 1 :(得分:0)

您可以使用DB::select方法来检索结果。

use Illuminate\Support\Facades\DB;


$results = DB::select("SELECT * 
FROM ( SELECT * 
FROM ( SELECT * 
   FROM question_responses ) AS A
JOIN ( SELECT survey_response_id AS JOIN_A
   FROM question_responses
   WHERE (question_short_name = ?) AND (value = ?)) AS B
ON A.survey_response_id= JOIN_A) AS C
JOIN ( SELECT survey_response_id AS JOIN_B
   FROM question_responses
   WHERE (question_short_name = ?) AND (value = ?)) AS D
ON C.survey_response_id= JOIN_B", ['Gender', 'Male', 'Age', '45 to 54']);

foreach ($results as $key => $row) {
    print_r($row);
}