Many to Many to MorphToMany Relationships

自古美人都是妖i 提交于 2021-01-29 13:42:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!