使用RAW表达式的LEFT JOIN的Laravel数据库查询构建器

时间:2018-01-26 05:42:38

标签: mysql laravel eloquent laravel-eloquent laravel-query-builder

我想left join来自many-to-many关系的数据。在我第一次尝试解决问题时,我最终得到了How can a LEFT OUTER JOIN return more records than exist in the left table?

中描述的情况

现在我认为在many-to-many之前我连接了left join关系中的值,但是我再次陷入困境并且没有到达任何地方。我设法提出了部分解决方案,但我不知道如何将它们组合到最终解决方案中。

查询

SELECT 
    groups.id as `groups.id`, 
    GROUP_CONCAT(choices.text) AS choices
FROM `input-choices` choices
    LEFT JOIN `input-choice_input-group` pivot ON choices.id = `pivot`.`input-choice_id`
    LEFT JOIN `input-groups` groups ON groups.id = `pivot`.`input-group_id`
WHERE groups.id = 2
GROUP BY groups.id

WHERE groups.id = 2最终会更改为WHERE groups.id = `input-types`.`input-group.id`

产生e。 G。结果集如:

groups.id | choices 
2         | 1,2,3,4,5

下一步我认为将上一个查询的结果与Query Builder DB::raw()方法联系起来是有意义的,但我再次陷入困境。

$survey = DB::table('questions')
->join('question_survey', function ($join) {
    $join->on('questions.id', '=', 'question_survey.question_id')
        ->where('question_survey.survey_id', '=', 1);
})
->leftJoin('answer_question_survey', 'question_survey.id', '=', 'answer_question_survey.question_survey_id')
->leftJoin('answers', 'answer_question_survey.answer_id', '=', 'answers.id')
->leftJoin('input-types', 'input-types.id', '=', 'questions.input-type_id')
->leftJoin(DB::raw(...), 'input-types.input-group.id', '=', '?.groups.id')
->select(
    'questions.id AS question.id',
    'questions.text AS question.text',
    'questions.explanation AS question.explanation',
    'questions.is_required AS question.is_required',
    'questions.input-type_id AS question.input-type_id',
    'input-types.id AS input-type.id',
    'input-types.name AS input-type.name',
    'input-types.input-group_id AS input-type.input-group_id',
    'question_survey.id AS question_survey.id',
    'question_survey.question_id AS question_survey.question_id',
    'question_survey.survey_id AS question_survey.survey_id',
    'question_survey.parent_id AS question_survey.parent_id',
    'answer_question_survey.id AS answer_question_survey.id',
    'answer_question_survey.question_survey_id AS answer_question_survey.question_survey_id',
    'answer_question_survey.answer_id AS answer_question_survey.answer_id',
    'answers.id AS answer.id',
    'answers.text AS answer.text'
)
->get();
  1. 如何使用DB::raw()方法中的第一个查询。我总是收到类似"语法错误或访问冲突的错误:..."
  2. 我如何完成加入条件'input-types.input-group.id', '=', '?.groups.id',因为我不知道我加入的桌子的名称。

1 个答案:

答案 0 :(得分:0)

  

尝试将您的子查询放入选择部分作为DB :: raw()。