如何在拉拉维尔中计数和获取数据查询


How to count and fetch data query in laravel?

如何合并这两个查询?

$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类型,它为集合提供了方便的函数,其中一个是count()不要与上面提到的聚合函数混淆 - 你又回到了PHP,而不是MySQL)。

因此,$data->count()为您提供集合中的项目数量(这几乎是类固醇上的数组),甚至没有命中数据库。

嗨数据库类不返回集合对象,

它给出错误"在数组上调用成员函数",但雄辩地返回集合对象。 对于上面的代码,我们可以使用收集辅助函数使其成为集合实例,然后使用 count 和其他收集方法 https://laravel.com/docs/5.1/collections#available-methods。

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

你我得到它使用:

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

要获取计数,请尝试以下操作:

$data->count();

为什么使用 DB::table(...) ,相反,您可以使用这样的模型Eloquentmodels 目录中创建模型:

class CategoryToNews extends Eloquent {
    protected $table = 'category_to_news';
    protected $primaryKey = 'id'; // if different than id then change it here
}

现在,您可以轻松使用:

$data = CategoryToNews::whereName(ucwords($category))->get();

若要获取计数,请使用:

$data->count();