首页 > 解决方案 > 雄辩的关系 - 通过数据透视表获取唯一的条目列表。(BelongsToMany)

问题描述

通过 belongsToMany 关系,我可以根据分配给目录的问题的数量获得一组主题。因此,此列表包含许多重复项。我不确定我是否可能误解了关系模型,或者我是否应该通过不同的或数组操作过滤掉。

所以让我们假设我们有三个表目录主题问题。而一个问题属于一个目录和一个主题。因此,目录主题可能有很多问题。目录和主题之间的链接是在问题表中建立的。

现在我想通过 q​​uestions 显示属于特定目录的所有主题(一个不同列表

有关说明,请参阅以下内容:

| id | created_at          | updated_at          | title            | is_active | pivot_catalogue_id | pivot_topic_id |
|----|---------------------|---------------------|------------------|-----------|--------------------|----------------|
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 1      | 1         | 1                  | 1              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 1      | 1         | 1                  | 1              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 1      | 1         | 1                  | 1              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 1      | 1         | 1                  | 1              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 1      | 1         | 1                  | 1              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 2      | 1         | 1                  | 2              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 2      | 1         | 1                  | 2              |
| 1  | 2020-01-22 11:51:41 | 2020-01-22 11:51:41 | Topic 2      | 1         | 1                  | 2              |

ER图 ER图

目录型号

    /**
     * Get the corresponding questions of a catalogue.
     *
     */
    public function Questions()
    {
        return $this->hasMany(Question::class);
    }

    /**
     * Get the corresponding topics through questions of a catalogue.
     *
     */
    public function Topics(): belongsToMany
    {
        return $this->belongsToMany(Topic::class, Question::class);
    }

主题模型

    /**
     * Get the corresponding questions for a topic.
     *
     */
    public function Question()
    {
        return $this->hasMany(Question::class);
    }

问题模型

    /**
     * Get the corresponding catalogue for the question.
     *
     */
    public function catalogue()
    {
        return $this->belongsTo(Catalogue::class);
    }

    /**
     * Get the corresponding topic for the question.
     *
     */
    public function topic()
    {
        return $this->belongsTo(Topic::class);
    }

标签: laravelrelationshiphas-and-belongs-to-many

解决方案


您可以从目录中定义 BelongsToMany 关系:

class Catalogue extends Model
{
    public function topics()
    {
        return $this->belongsToMany(Topic::class, 'questions');
    }
}

但是问题表将包含具有 catalogue_id 和 topic_id 的 DUPLICATE 组合的记录,因此 $catalogue->topics 将返回 DUPLICATE 主题。

我们可以做的最简单的事情是为关系放置 distinct() 。

public function topics()
{
    return $this->belongsToMany(Topic::class, 'questions')->distinct();
}

所以这将删除重复的主题。


推荐阅读