多对多关系 [英] Many to Many to MorphToMany Relationships

查看:83
本文介绍了多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个考试问题标记(Spatie/laravel-tags软件包)模型.

I have an Exam, Question and Tag (Spatie/laravel-tags package) models.

考试由很多问题(很多)组成,而 Question 有很多 Tags (MorphToMany).

An Exam consists of many Questions (Many to Many), and Question has many Tags (MorphToMany).

我想在Exam模型上有一个方法来通过其关联的问题获取Exam的所有标签,以便 $ exams→tags()返回属于的关联问题的所有标签考试.

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?

推荐答案

如果您具有适当的描述关系,只需编写如下内容:

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();
}

这篇关于多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆