首页 > 解决方案 > 使用标签字段模块时,如何在 Silverstripe 中按标签过滤?

问题描述

我在 Silverstripe 中有以下页面类型,其中包含许多 CategoryTag。CategoryTag 是使用 silverstripe-tagfield 模块创建的数据对象。

class ArticlePage extends Page {
 ...
  private static $many_many = array(
            'CategoryTags' => 'CategoryTag'
        );
...

我想将具有匹配 CategoryTags 的所有其他 ArticlePages 返回到当前页面。我知道我可以返回所有其他 ArticlePages 并过滤它们,例如:

public function getRelatedArticles() {
            $relatedArticles = ArticlePage::get()->filter(SOME FILTER);
             return ($relatedArticles);
         }

但我不确定按当前页面的 CategoryTags 过滤的语法。我将如何调整上述功能来实现这一目标?提前致谢。

标签: phpsilverstripe

解决方案


经过相当多的挠头,我找到了一个解决方案:

 public function getRelatedArticles(){
    return ArticlePage::get()->filter('CategoryTags.ID', $this->CategoryTags()->column('ID'))->exclude('ID', $this->ID);
 }

希望这可以为将来节省一些时间:)


推荐阅读