CakePHP 3.x - 如果实际上不需要,为什么要编写查询?
CakePHP 3.x - why write a query if it's not actually required?
在 CakePHP 3.x 的(令人难以置信的混乱)文档中,它在 New ORM Upgrade Guide 下给出了以下内容:
You can decorate queries with iterators and call methods without even touching the database. This is great when you have parts of your view cached and having the results taken from the database is not actually required:
// No queries made in this example!
$results = $articles->find()
->order(['title' => 'DESC'])
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->extract('title');
});
为什么 上面的代码,如果 "having the results taken from the database is not actually required"?
你必须在它嵌入的上下文中阅读它,整个部分都是关于“如何在 table 上调用 find
不会 return 立即得到结果,但会 return 一个 Query 对象 ",在什么情况下会很有用。
查询对象不会自动生成 运行 SQL,它们仅在显式调用特定方法(如 toArray()
、all()
、集合方法等)时才会自动生成,或者在迭代对象时。
那里描述的情况是当您的代码中查询对象最终被执行的部分,即实际的 SQL 查询正在构建并且 运行 已被缓存(例如一个视图模板),因此 运行 在后续请求中再次查询将毫无意义,只会产生不必要的开销,因为您已经有了缓存的结果。
另见
在 CakePHP 3.x 的(令人难以置信的混乱)文档中,它在 New ORM Upgrade Guide 下给出了以下内容:
You can decorate queries with iterators and call methods without even touching the database. This is great when you have parts of your view cached and having the results taken from the database is not actually required:
// No queries made in this example!
$results = $articles->find()
->order(['title' => 'DESC'])
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->extract('title');
});
为什么 上面的代码,如果 "having the results taken from the database is not actually required"?
你必须在它嵌入的上下文中阅读它,整个部分都是关于“如何在 table 上调用 find
不会 return 立即得到结果,但会 return 一个 Query 对象 ",在什么情况下会很有用。
查询对象不会自动生成 运行 SQL,它们仅在显式调用特定方法(如 toArray()
、all()
、集合方法等)时才会自动生成,或者在迭代对象时。
那里描述的情况是当您的代码中查询对象最终被执行的部分,即实际的 SQL 查询正在构建并且 运行 已被缓存(例如一个视图模板),因此 运行 在后续请求中再次查询将毫无意义,只会产生不必要的开销,因为您已经有了缓存的结果。
另见