问题
I have an Exam, Question and Tag (Spatie/laravel-tags package) models.
An Exam
consists of many Questions
(Many to Many), and Question
has many Tags
(MorphToMany).
I would like to have a method on the Exam model to get all the tags of Exam through its associated questions, such that $exams→tags()
returns all the tags from associated questions belonging to the exam.
Can anyone point me towards what may be the best course to take in order to achieve this?
回答1:
If you have proper described relations, just write something like that:
// Exam Model
public function tags()
{
return $this->questions->map(function($q){
return $q->tags;
})->collapse();
}
回答2:
you can get all the tags from exams like this
return Exam::with('questions.tags')->get();
If u want some conditions for tags you can do like this
return Exam::with(['questions.tags'=> function($query){
$query->where('..','..')
}])->get();
If u want a proper function inside your model like you said just put the logic inside one function in. your model like this
Exam.php
public function getAllTags()
{
return $this->with(['questions.tags'=> function($query){
$query->select('..');
}])->get();
}
// This will just give you what you need
Let me know if this helps
来源:https://stackoverflow.com/questions/61657901/many-to-many-to-morphtomany-relationships