gpt4 book ai didi

php - laravel中如何统计和获取数据查询?

转载 作者:行者123 更新时间:2023-11-29 05:23:30 25 4
gpt4 key购买 nike

如何合并这两个查询?

$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->count();

$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->get();

最佳答案

因此,据我从您的评论中了解到,您只是想从表 category_to_news 中获取所有 记录,并且您想知道其中有多少条记录,对吧?

MySQL 的count 是一个聚合函数,这意味着:它获取一组值,执行计算并返回一个单个 值。如果将它放入您的姓名查询中,您将在每条记录中获得相同的值。我不确定这是否与“优化”有关。

如前所述,您只需照常运行查询即可:

$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get(['title']);

$data 现在属于 Illuminate\Support\Collection 类型,它提供 handy functions for collections ,其中一个是 count()(不要与上面提到的聚合函数混淆 - 您又回到了 PHP,而不是 MySQL)。

因此 $data->count() 甚至无需访问数据库即可为您提供集合中项目的数量(这几乎是类固醇数组)。

关于php - laravel中如何统计和获取数据查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22907350/

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