如何从 CakePHP 3 的结果集中删除项目?
How to remove an item from a resultset in CakePHP 3?
我想从结果集中删除一些指定的项目
这意味着我最后需要一个 ResultSet 对象。
有什么方法可以从 ResultSet 中删除一个项目或从现有的 ResultSet 中创建另一个 ResultSet?
我试过使用 filter() 或 reject()。
但是,他们没有 return ResultSet 对象?
$ids = [123, 234, 456];
$results = $this->find()
->where(['xxx' => 'xxxx'])
->all();
$newResults = $results->filter(function ($result) {
return in_array($result->id, $ids);
});
我会质疑您是否真的需要一个结果集,即实现\Cake\Datasource\ResultSetInterface
.
的对象
结果集接口只是\Cake\Collection\CollectionInterface
、\Countable
, and \Serializable
的组合,CakePHP的正则集合class几乎可以满足,即\Cake\Collection\Collection
,只是欠缺\Countable::count()
。因此,您的 filter()
调用返回的集合在大多数情况下应该可以满足您的需求。
如果由于某种原因你将被迫通过一个 \Cake\Datasource\ResultSetInterface
实现,并且你绝对不能出于任何原因更改该合同,那么你总是可以将你的数据传递给一个新的结果集装饰器:
$resultSet = new \Cake\Datasource\ResultSetDecorator($collection->toArray());
您还可以在查询级别操作您的数据,方法是不首先检索您不想要的数据,即在您的 where()
条件中排除它们,或者通过过滤 a result formatter,那么您将直接从查询中收到一个简化的 \Cake\Datasource\ResultSetInterface
对象:
$results = $this
->find()
->where(['xxx' => 'xxxx'])
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->filter(/* ... */);
})
// ...
我想从结果集中删除一些指定的项目 这意味着我最后需要一个 ResultSet 对象。
有什么方法可以从 ResultSet 中删除一个项目或从现有的 ResultSet 中创建另一个 ResultSet?
我试过使用 filter() 或 reject()。 但是,他们没有 return ResultSet 对象?
$ids = [123, 234, 456];
$results = $this->find()
->where(['xxx' => 'xxxx'])
->all();
$newResults = $results->filter(function ($result) {
return in_array($result->id, $ids);
});
我会质疑您是否真的需要一个结果集,即实现\Cake\Datasource\ResultSetInterface
.
结果集接口只是\Cake\Collection\CollectionInterface
、\Countable
, and \Serializable
的组合,CakePHP的正则集合class几乎可以满足,即\Cake\Collection\Collection
,只是欠缺\Countable::count()
。因此,您的 filter()
调用返回的集合在大多数情况下应该可以满足您的需求。
如果由于某种原因你将被迫通过一个 \Cake\Datasource\ResultSetInterface
实现,并且你绝对不能出于任何原因更改该合同,那么你总是可以将你的数据传递给一个新的结果集装饰器:
$resultSet = new \Cake\Datasource\ResultSetDecorator($collection->toArray());
您还可以在查询级别操作您的数据,方法是不首先检索您不想要的数据,即在您的 where()
条件中排除它们,或者通过过滤 a result formatter,那么您将直接从查询中收到一个简化的 \Cake\Datasource\ResultSetInterface
对象:
$results = $this
->find()
->where(['xxx' => 'xxxx'])
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->filter(/* ... */);
})
// ...