1

所以我有一个变量和一个记录集:

$firstRecordID = 1;
$records = Recordset::all();

我想过滤记录集:

$filteredRecords = $records->find(function($record) use ($firstRecordID){
    return ($record->id == $firstRecordID);
});

在这个例子中,假设记录 id 是一个主键,只有一行会被返回,但是,我认为过滤器会继续运行。

我的问题是,如何在满足特定条件后强制过滤器停止?

编辑:我将添加另一个更复杂的示例:

$filteredRecords = $records->find(function($record) use ($lastRecordID){
    $conditions == $records->conditions;
    // in here I would find some value 
    // based on some other unknown record based on the $conditions

    // if the value matches any of the $conditions return the row
    // if the value matches a specified stop condition 
    // (which is defined by the user) stop retrieving rows.
});
4

2 回答 2

0

我认为解决方案是先使用($filter)

$filteredRecords = $records->first(function($record) use ($firstRecordID){
    return ($record->id == $firstRecordID);
});

http://li3.me/docs/lithium/util/Collection::first

于 2012-02-22T09:35:46.447 回答
-1

简短的回答

在过滤器内部抛出异常并在外部捕获它。您可能必须自己收集包含在数组中的项目,因为您无法访问find' 的返回值。

长答案

find当您退后一步考虑您要完成的工作可能对您有所帮助时,您过于关注特定策略(停止使用过滤器)。

老实说,这听起来就像您想吃蛋糕并拥有它:您想要灵活并在一个您可以轻松更改的函数中指定您的搜索条件,但您也想要高效而不是从数据库中提取更多数据比你必须的。

问题是,将过滤器函数传递到find您的过滤器效率已经很低了,因为 li3 必须在调用过滤器之前从数据库中提取每条记录。这就是效率低下的地方。一旦你达到 10 个项目或任何不会产生太大影响的东西就停止过滤过程(除非你的过滤也非常昂贵)。

我建议考虑以下几点:

  1. 你真的需要允许任何过滤方法吗?是否可以使用声明性条件?如果是这样,您可以提供limit选项并让数据库完成所有工作。

  2. 如果不能,请考虑使用find获取一小批记录并收集要保留在数组中的记录。重复另一个小批量,直到您检查了数据库中的每个项目或填充了您的数组。

于 2012-02-23T20:32:29.483 回答