Silverstripe ExactMatchFilter 示例

Silverstripe ExactMatchFilter example

我有一个数据对象列表,我正在尝试 return 匹配特定年份的所有对象,例如匹配 2015、2013、2002 等的所有对象

我首先尝试根据此处的问题使用 ExactMatchMultiSilverstripe - filter DataObject list by many many relationship

但是现在已经弃用了,Silverstripe 建议我改用 ExactMatchFilter。但是我找不到 ExactMatchFilter 的很多 documentation/code 用法,所以我不确定如何使用它。将 ExactMatchMulti 替换为 ExactMatchFilter 会引发异常。

$things->filter('PublicationDate:ExactMatchFilter', $filters);

其中 $filters 只是一个简单的年份数组。

有人对此有任何示例或建议吗?

(使用 3.2.1)

异常详细信息是添加到问题中的好东西。

我认为在日期字段上使用完全匹配过滤器在逻辑上不会像您想象的那样起作用。该字段是否准确包含 2015 年,还是包含日期时间戳?我假设是后者,因为您的字段名称是 PublicationDate。

这是我们用来按年份过滤的:

NewsItem()->get()->filter('Date:StartsWith', $year)

或者您也可以按年份过滤大于和小于集合。

编辑:

示例查询未在 3.2.1 上测试,但应该有效。

通过使用过滤器 any 你可以通过 OR 获得多个(基于 https://docs.silverstripe.org/en/3.2/developer_guides/model/data_model_and_orm/#filterany):

 NewsItem()->get()->filterAny("Date:StartsWith",array('2015','2014'));

然后用你想要的正确年份生成数组。

提示:

使用 ->sql() 查看 sql 查询是什么: Debug::dump(NewsItem()->get()->filterAny("Date:StartsWith",array('2014','2015'))->sql());

编辑:修正双键问题。

在 DataList 中,措辞 'Filter' 不应出现在 filter() 函数中。

正确的语法应该是

$things->filter('PublicationDate:ExactMatch', $filters);

看过https://github.com/silverstripe/silverstripe-framework/blob/3.2.1/search/filters/ExactMatchFilter.php#L51

将 array() 传递给 ExactMatchFilter 应该可以满足您的要求。

其实很简单,只是一个疏忽。工作示例:

public function getPagesByFilter() {
    $filters = array('2015', '2014');
    Page::get()->filterAny('PublicationDate:PartialMatch', $filters);
}

如上所述,简单明了的事情是使用 filterAny 而不仅仅是过滤器。这将 return 发布日期为 2015 年和 2014 年的所有页面。