Laravel: 不同表的多次计数

Laravel: Multiple count for different tables

我有三个不同的 eloquent 查询来获取我的表的计数。

$posts = Post::where('published', true)->count();
$pages = Pages::where('published', true)->count();
$products = Product::where('published', true)->count();

有没有一个唯一的 Eloquent 查询的方法? (如果可能的话,我不想使用DB::raw)。

谢谢!

像在单个查询中一样编写代码。

$data = DB::select("SELECT (SELECT COUNT(*) FROM posts WHERE published = true) as post_count, (SELECT COUNT(*) FROM pages WHERE published = true) as page_count, (SELECT COUNT(*) FROM products WHERE published = true) as product_count");

之后你可以得到像这样的记录

$data->post_count
$data->page_count
$data->product_count