gpt4 book ai didi

CakePHP3 删除afterFind后,查询结果是否为空,去哪里检查?

转载 作者:行者123 更新时间:2023-12-02 01:11:54 27 4
gpt4 key购买 nike

如果查找结果为空,我检查 afterFind 回调之前。由于回调在最新版本中被删除,在哪里可以从行为中检查回调?

我不确定这是否是我需要的。我的用例是,我想知道查询是否没有结果。然后我会创建一个默认条目,因此它有 1 个结果。

最佳答案

https://book.cakephp.org/3.0/en/appendices/orm-migration.html#no-afterfind-event-or-virtual-fields

Once defined you can access your new property using $user->full_name. Using the Modifying Results with Map/Reduce features of the ORM allow you to build aggregated data from your results, which is another use case that the afterFind callback was often used for.

在 ResultSet 对象上调用 count()

https://api.cakephp.org/3.4/class-Cake.ORM.ResultSet.html#_count

不知道您为什么不使用它并想手动计数,但请继续。

使用 resultFormatter()

https://book.cakephp.org/3.0/en/orm/query-builder.html#adding-calculated-fields

您的行为必须将 beforeFind() 中的格式化程序添加到查询中。您也可以添加添加它的自定义查找。示例代码(取自文档):

$query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->map(function ($row) {
$row['age'] = $row['birth_date']->diff(new \DateTime)->y;
return $row;
});
});

在那里计算结果。

使用映射/归约

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#map-reduce

More often than not, find operations require post-processing the data that is found in the database. While entities’ getter methods can take care of most of the virtual property generation or special data formatting, sometimes you need to change the data structure in a more fundamental way.

您的行为必须将 beforeFind() 中的映射器/缩减器添加到查询中。您也可以添加添加它的自定义查找。示例代码(取自文档):

$articlesByStatus = $articles->find()
->where(['author_id' => 1])
->mapReduce($mapper, $reducer);

查看上面的链接以获得详细说明,包括如何创建映射器和缩减器的示例。

关于CakePHP3 删除afterFind后,查询结果是否为空,去哪里检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44904177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com