HasManyThrough关系包括一个枢轴

时间:2018-09-07 09:23:32

标签: laravel eloquent eloquent--relationship

我有一个模块问题类别模型。

Module hasMany Questions. (1 to Many)
Question belongsToMany Categories. (Many to Many)

对于给定的模块,我只想访问问题,其中 category_id = X

我不确定最有效的方法是什么。我可以通过Module和Category之间的HasManyThrough关系来做到吗?还是我必须创建一个循环?还是通过原始SQL查询来完成?

更新

此SQL查询似乎有效。但是,我确定必须有一个更优雅的解决方案?

SELECT id
FROM questions
INNER JOIN category_question ON questions.id = category_question.question_id 
WHERE category_question.category_id = X and module_id = Y;

2 个答案:

答案 0 :(得分:0)

您可以使用此实现

 Question::with(['module','categories'])
   ->join('category_question','category_question.question_id','=','question.id')
   ->where('category_question.category_id','=','X')
   ->where('questions.module_id','=','module_id')->get();

答案 1 :(得分:0)

Question::with(['model','categories'=>function($query){
    return $query->where('category_question.category_id',$category_id);
}])->get();

希望这行得通。