laravel:连接多个select语句

dbf7pr2w  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(443)

我有一个调查应用程序。每个 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的查询生成器来实现这一点?

6jjcrrmo

6jjcrrmo1#

你可以用 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);
}
jm2pwxwz

jm2pwxwz2#

您可以使用雄辩的关系,但是如果您想使用这种特定类型的查询,那么您可以使用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;

相关问题