HasManyThrough 关系包括一个枢轴

HasManyThrough Relations includes a Pivot

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

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;

你可以使用这个实现

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

希望这能奏效。