laravel - 雄辩的关系 - 通过数据透视表获取唯一的条目列表。(BelongsToMany)
问题描述
通过 belongsToMany 关系,我可以根据分配给目录的问题的数量获得一组主题。因此,此列表包含许多重复项。我不确定我是否可能误解了关系模型,或者我是否应该通过不同的或数组操作过滤掉。
所以让我们假设我们有三个表目录、主题、问题。而一个问题属于一个目录和一个主题。因此,目录和主题可能有很多问题。目录和主题之间的链接是在问题表中建立的。
现在我想通过 questions 显示属于特定目录的所有主题(一个不同的列表)。
有关说明,请参阅以下内容:
| 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 |
目录型号
/**
* 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);
}
解决方案
您可以从目录中定义 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();
}
所以这将删除重复的主题。
推荐阅读
- python - 如何组合两个逻辑相同但输入参数不同的函数?
- javascript - 将 d3 Sunburst 图表的度数从 360 更改为另一个值(并隐藏部分)
- java - 如何测量物体之间的距离?
- vba - 将单词列表插入单词/创建句子
- time-complexity - 这种方法的时间复杂度是多少?
- xampp - 当xampp无法在mac Big Sur中打开时如何访问htdocs文件夹?
- jekyll - CloudCannon 自动构建未在指定日期和时间运行
- curl - Curl 超时 - 错误 28 - VPS 到另一个 VPS 连接
- mongodb - 如何将 Mongo DB ec2 实例更改为多节点
- python - 熊猫用另一列中的值替换列中的值