Laravel对三个表

时间:2017-04-15 14:00:48

标签: mysql sql database laravel-5.2

我是laravel的新手,我创建了一个在Xampp服务器中完美运行的查询,现在我想在laravel中转换此查询,我创建了一个laravel代码,显示错误SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'question_chapter_rel' (SQL: select count(*) as aggregate from question_chapter_rel {{1 }} question_chapter_rel inner join章节on ID:. question_chapter_rel = chapter_id .问题inner join问题on ID:. question_chapter_rel = question_id .答案inner join答案on ID:.问题= correct_answers .答案where is_correct { {1}}

这是我的laravel查询:

.

这是我要转换的代码

= 1)

提前致谢

question_chapter_rel表question_chapter_rel Table章节表chapter Table问题表question Table答案表answers Table

2 个答案:

答案 0 :(得分:0)

始终可以使用DB :: raw。检查laracast docs https://laravel.com/docs/5.4/queries#joins

中的join语句

检查这个

请添加使用DB;

public function scopeGetQuestion($query)
{
    dd(DB::table('chapters')->select('chapters.id', 'chapters.chapter_description', 'questions.id', 'questions.question_description', 'answers.id', 'answers.answer_description')->join('question_chapter_rel', 'chapters.id', '=' ,'question_chapter_rel.chapter_id')->join('questions','questions.id', '=' ,'question_chapter_rel.question_id')->join('answers','answers.id', '=' ,'questions.correct_answers')->where('answers.is_correct', '=' ,1)->get());
    return;
}

答案 1 :(得分:0)

This how its works, From the first line use **chapter** instead **question_chapter_rel**


  public function scopeGetQuestion($query,$id)
        {

            return $query->join('chapters', 'chapters.id', '=' ,'question_chapter_rel.chapter_id')
                ->join('questions','questions.id', '=' ,'question_chapter_rel.question_id')
                ->join('answers','answers.id', '=' ,'questions.correct_answers')
                ->where('answers.is_correct',1)
                ->where('question_chapter_rel.chapter_id',$id)
                ->select(
                    [

                        'chapters.id',
                        'chapters.chapter_description',
                        'questions.id',
                        'questions.question_description',
                        'answers.id',
                        'answers.answer_description'
                    ]
                )


            ->paginate(20);
        }