使用 Laravel Eloquent 在一次数据库访问中从 3 个表中获取 3 个计数

问题描述 投票:0回答:2

我有三个不同的雄辩查询来获取我的表的数量。

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

有办法拥有独特的 Eloquent 查询吗?

我担心查询的安全性,所以如果可能的话,我想避免

DB::raw

php laravel eloquent count
2个回答
2
投票

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

$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

0
投票

如果您想尽可能多地使用查询构建器方法,那么这里有另一种方法,其中将附加子查询输入到 SELECT 子句中:(PHPize Demo)

var_export(
    DB::table('Post')
    ->whereRaw('published = true')
    ->selectRaw('COUNT(*) posts')
    ->selectRaw('(' . DB::table('Pages')->whereRaw('published = true')->selectRaw('COUNT(*)')->toSql() . ') pages')
    ->selectRaw('(' . DB::table('Products')->whereRaw('published = true')->selectRaw('COUNT(*)')->toSql() . ') products')
    //->toSQL()
    ->get()
    ->first()
);

我无法按照

laravel Eloquent ORM - 如何获取已编译的查询?
中的建议在沙箱中实现 ->toSqlWithBindings() ...但这在这里看起来非常有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.