我是 laravel 的新手,我创建了一个在 Xampp 服务器中完美运行的查询,现在我想在 laravel 中转换这个查询,我创建了一个显示错误的 laravel 代码 SQLSTATE[42000]: Syntax错误或访问冲突:1066 不是唯一的表/别名:'question_chapter_rel'(SQL:从
question_chapter_rel内部联接
question_chapter_rel章节中选择计数(*)
.
id=
question_chapter_rel.
chapter_id内联
questionson
questions.
id=
question_chapter_rel.
question_id内连接
answerson
answers.
id=
questions.
correct_answerswhere
answers.
is_correct= 1)
这是我的 laravel 查询:
public function scopeGetQuestion($query)
{
return $query->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')
->select(
[
'chapters.id',
'chapters.chapter_description',
'questions.id',
'questions.question_description',
'answers.id',
'answers.answer_description'
]
)
->where('answers.is_correct',1)
->paginate(12);
}
这是我要转换的代码
select `chapters`.`id`, `chapters`.`chapter_description`, `questions`.`id`, `questions`.`question_description`, `answers`.`id`, `answers`.`answer_description`
from `chapters`
Inner Join `question_chapter_rel`
on `chapters`.`id` = `question_chapter_rel`.`chapter_id`
Inner Join `questions`
on `questions`.`id` = `question_chapter_rel`.`question_id`
Inner Join `answers`
on `answers`.`id` = `questions`.`correct_answers`
where `answers`.`is_correct` = 1
提前致谢
最佳答案
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);
}
关于mysql - Laravel 多表查询三张表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426961/