I have 4 models with the relevant migrations / tables:
-topics
-question_topic
-questions
-responses
Topics and questions are linked via the intermediate questions_topic table in a many-to-many relationship.
Questions are related to responses in a one-to-many relationship.
I need to be able to show a random selection of x questions for a specific topic and the related responses. I am however struggling to write the correct eloquent query.
I can get all the questions for a specific topic:
$questions = Topic::where('id',1)->with('questions')->get();
I can randomly get 10 questions and related responses, but not using topic to group as I need to:
$questions = Question::with('responses')->inRandomOrder()->limit(10)->get();
If I do something like this, the limit only applies to the topic, so I get all of the questions and responses for the specified topic. The random order would also not work here.
$questions = Topic::with('questions.responses')->where('id', 1)->limit(1)->get();
Any pointers as to how I should best proceed would be much appreciated!