WPDB 包装和查询构建库。

1.1.1 2024-06-06 20:03 UTC

This package is auto-updated.

Last update: 2024-09-21 18:05:28 UTC


README

Tests Static Analysis

WPDB 包装和查询构建库。由 StellarWP 开发团队编写,免费提供给 WordPress 社区。

灵感来源于,并且大部分是从 GiveWP 代码库中 fork 出来的!

安装

建议您通过 Composer 将 DB 作为项目依赖项安装

composer require stellarwp/db

我们实际上建议使用 Strauss 将此库包含到您的项目中。

幸运的是,将 Strauss 添加到您的 composer.json 比添加一个典型的依赖项稍微复杂一点,所以请查看我们的 strauss 文档

目录

快速入门

使用此库很容易上手。您需要初始化 DB 类。在 plugins_loaded 动作期间这样做是合理的,尽管您可以在任何感觉合适的地方这样做。

对于这个示例以及所有未来的示例,让我们假设您已经通过 包含此库 使用 Strauss,并且您的项目命名空间是 Boom\Shakalaka

use Boom\Shakalaka\StellarWP\DB\DB;

add_action( 'plugins_loaded', function() {
	DB::init();
}, 0 );

构成此库核心的两个主要类是 DB 类和 QueryBuilder 类。以下是它们的命名空间

# For DB, it is "StellarWP\DB\DB", but with your namespace prefix it'll be:
use Boom\Shakalaka\StellarWP\DB\DB;

# For QueryBuilder, it is "StellarWP\DB\QueryBuilder\QueryBuilder", but with your namespace prefix it'll be:
use Boom\Shakalaka\StellarWP\DB\QueryBuilder\QueryBuilder;

配置

此库提供默认钩子和异常,但是,如果您自己的应用程序有额外需求,您可以通过 StellarWP\DB\Config 类重写一个或两个。

use Boom\Shakalaka\StellarWP\DB\Config;

// Ensure hooks are prefixed with your project's prefix.
Config::setHookPrefix( 'boom_shakalaka' );

// Use your own exception class rather than the default Database\Exceptions\DatabaseQueryException class.
Config::setDatabaseQueryException( 'MyCustomException' );

// Fetch the hook prefix.
$prefix = Config::getHookPrefix();

// Fetch the database query exception class.
$class = Config::getDatabaseQueryException();

DB

DB 类是 $wpdb 类的静态装饰器,但它有一些例外方法。方法 DB::table()DB::raw()

DB::table()QueryBuilder 类的静态外观,它接受两个字符串参数,$tableName$tableAlias

在内部,DB::table() 将创建一个新的 QueryBuilder 实例,并使用 QueryBuilder::from 方法设置表名。在调用 QueryBuilder::from 时使用 DB::table 方法将返回一个意外的结果。基本上,我们在告诉 QueryBuilder 我们想要从两个表中选择数据。

重要

当使用 DB::table(tableName) 方法时,tableName 前缀为 $wpdb->prefix。要绕过这一点,您可以使用 DB::raw 方法,这将告诉 QueryBuilder 不要给表名添加前缀。

DB::table(DB::raw('posts'));

选择语句

可用方法 - select / selectRaw / distinct

通过使用QueryBuilder::select方法,您可以指定查询的定制SELECT语句。

DB::table('posts')->select('ID', 'post_title', 'post_date');

生成的SQL

SELECT ID, post_title, post_date FROM wp_posts

您还可以通过向QueryBuilder::select方法提供一个数组[列, 别名]来指定列别名。

DB::table('posts')->select(
    ['ID', 'post_id'],
    ['post_status', 'status'],
    ['post_date', 'createdAt']
);

生成的SQL

SELECT ID AS post_id, post_status AS status, post_date AS createdAt FROM wp_posts

distinct方法允许您强制查询返回不同的结果

DB::table('posts')->select('post_status')->distinct();

您还可以使用QueryBuilder::selectRaw方法指定定制SELECT语句。此方法接受一个可选的绑定数组作为其第二个参数。

DB::table('posts')
    ->select('ID')
    ->selectRaw('(SELECT ID from wp_posts WHERE post_status = %s) AS subscriptionId', 'give_subscription');

生成的SQL

SELECT ID, (SELECT ID from wp_posts WHERE post_status = 'give_subscription') AS subscriptionId FROM wp_posts

默认情况下,将从数据库表中选择所有列。

DB::table('posts');

生成的SQL

SELECT * FROM wp_posts

From子句

通过使用QueryBuilder::from()方法,您可以指定查询的定制FROM子句。

$builder = new QueryBuilder();
$builder->from('posts');

设置多个FROM子句

$builder = new QueryBuilder();
$builder->from('posts');
$builder->from('postmeta');

生成的SQL

SELECT * FROM wp_posts, wp_postmeta

重要

表名以$wpdb->prefix为前缀。要绕过这一点,您可以使用DB::raw方法,这将告诉QueryBuilder不要在表名前加前缀。

$builder = new QueryBuilder();
$builder->from(DB::raw('posts'));

连接

查询构建器还可以用于向查询添加JOIN子句。

可用方法 - leftJoin / rightJoin / innerJoin / joinRaw / join

LEFT Join

LEFT JOIN子句。

DB::table('posts', 'donationsTable')
    ->select('donationsTable.*', 'metaTable.*')
    ->leftJoin('give_donationmeta', 'donationsTable.ID', 'metaTable.donation_id', 'metaTable');

生成的SQL

SELECT donationsTable.*, metaTable.* FROM wp_posts AS donationsTable LEFT JOIN wp_give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id

RIGHT Join

RIGHT JOIN子句。

DB::table('posts', 'donationsTable')
    ->select('donationsTable.*', 'metaTable.*')
    ->rightJoin('give_donationmeta', 'donationsTable.ID', 'metaTable.donation_id', 'metaTable');

生成的SQL

SELECT donationsTable.*, metaTable.* FROM wp_posts AS donationsTable RIGHT JOIN wp_give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id

INNER Join

INNER JOIN子句。

DB::table('posts', 'donationsTable')
    ->select('donationsTable.*', 'metaTable.*')
    ->innerJoin('give_donationmeta', 'donationsTable.ID', 'metaTable.donation_id', 'metaTable');

生成的SQL

SELECT donationsTable.*, metaTable.* FROM wp_posts AS donationsTable INNER JOIN wp_give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id

原始连接

将原始表达式插入到查询中。

DB::table('posts', 'donationsTable')
    ->select('donationsTable.*', 'metaTable.*')
    ->joinRaw('LEFT JOIN give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id');

生成的SQL

SELECT donationsTable.*, metaTable.* FROM wp_posts AS donationsTable LEFT JOIN give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id

高级连接子句

闭包将接收一个Give\Framework\QueryBuilder\JoinQueryBuilder实例

DB::table('posts')
    ->select('donationsTable.*', 'metaTable.*')
    ->join(function (JoinQueryBuilder $builder) {
        $builder
            ->leftJoin('give_donationmeta', 'metaTable')
            ->on('donationsTable.ID', 'metaTable.donation_id')
            ->andOn('metaTable.meta_key', 'some_key', $qoute = true);
    });

生成的SQL

SELECT donationsTable.*, metaTable.* FROM wp_posts LEFT JOIN wp_give_donationmeta metaTable ON donationsTable.ID = metaTable.donation_id AND metaTable.meta_key = 'some_key'

UNION

查询构建器还提供了一个方便的方法来“联合”两个或更多查询。

可用方法 - union / unionAll

联合

$donations = DB::table('give_donations')->where('author_id', 10);

DB::table('give_subscriptions')
    ->select('ID')
    ->where('ID', 100, '>')
    ->union($donations);

生成的SQL

SELECT ID FROM wp_give_subscriptions WHERE ID > '100' UNION SELECT * FROM wp_give_donations WHERE author_id = '10'

WHERE 子句

您可以使用查询构建器的where方法向查询添加WHERE子句。

WHERE

可用方法 - where / orWhere

DB::table('posts')->where('ID', 5);

生成的SQL

SELECT * FROM wp_posts WHERE ID = '5'

多次使用where

DB::table('posts')
    ->where('ID', 5)
    ->where('post_author', 10);

生成的SQL

SELECT * FROM wp_posts WHERE ID = '5' AND post_author = '10'

Where IN子句

可用方法 - whereIn / orWhereIn / whereNotIn / orWhereNotIn

QueryBuilder::whereIn方法检查给定列的值是否包含在给定的数组中

DB::table('posts')->whereIn('ID', [1, 2, 3]);

生成的SQL

SELECT * FROM wp_posts WHERE ID IN ('1','2','3')

您还可以传递一个闭包作为第二个参数,该闭包将生成一个子查询。

闭包将接收一个Give\Framework\QueryBuilder\QueryBuilder实例

DB::table('posts')
    ->whereIn('ID', function (QueryBuilder $builder) {
        $builder
            ->select(['meta_value', 'donation_id'])
            ->from('give_donationmeta')
            ->where('meta_key', 'donation_id');
    });

生成的SQL

SELECT * FROM wp_posts WHERE ID IN (SELECT meta_value AS donation_id FROM wp_give_donationmeta WHERE meta_key = 'donation_id')

Where BETWEEN子句

QueryBuilder::whereBetween方法检查列的值是否在两个值之间

可用方法 - whereBetween / orWhereBetween / whereNotBetween / orWhereNotBetween

DB::table('posts')->whereBetween('ID', 0, 100);

生成的SQL

SELECT * FROM wp_posts WHERE ID BETWEEN '0' AND '100'

Where LIKE子句

QueryBuilder::whereLike方法在列中搜索指定的模式。

可用方法 - whereLike / orWhereLike / whereNotLike / orWhereNotLike

DB::table('posts')->whereLike('post_title', 'Donation');

生成的SQL

SELECT * FROM wp_posts WHERE post_title LIKE '%Donation%'

Where IS NULL子句

QueryBuilder::whereIsNull方法检查列的值是否为NULL

可用方法 - whereIsNull / orWhereIsNull / whereIsNotNull / orWhereIsNotNull

DB::table('posts')->whereIsNull('post_author');

生成的SQL

SELECT * FROM wp_posts WHERE post_author IS NULL

Where EXISTS子句

QueryBuilder::whereExists方法允许您编写WHERE EXISTS SQL子句。QueryBuilder::whereExists方法接受一个闭包,该闭包将接收一个QueryBuilder实例。

可用方法 - whereExists / whereNotExists

DB::table('give_donationmeta')
    ->whereExists(function (QueryBuilder $builder) {
        $builder
            ->select(['meta_value', 'donation_id'])
            ->where('meta_key', 'donation_id');
    });

生成的SQL

SELECT * FROM wp_give_donationmeta WHERE EXISTS (SELECT meta_value AS donation_id WHERE meta_key = 'donation_id')

子查询 WHERE 子句

有时您可能需要构建一个比较子查询结果与给定值的WHERE子句。

DB::table('posts')
    ->where('post_author', function (QueryBuilder $builder) {
        $builder
            ->select(['meta_value', 'author_id'])
            ->from('postmeta')
            ->where('meta_key', 'donation_id')
            ->where('meta_value', 10);
    });

生成的SQL

SELECT * FROM wp_posts WHERE post_author = (SELECT meta_value AS author_id FROM wp_postmeta WHERE meta_key = 'donation_id' AND meta_value = '10')

嵌套 WHERE 子句

有时您可能需要构建一个具有嵌套WHERE子句的WHERE子句。

闭包将接收一个Give\Framework\QueryBuilder\WhereQueryBuilder实例

DB::table('posts')
    ->where('post_author', 10)
    ->where(function (WhereQueryBuilder $builder) {
        $builder
            ->where('post_status', 'published')
            ->orWhere('post_status', 'donation')
            ->whereIn('ID', [1, 2, 3]);
    });

生成的SQL

SELECT * FROM wp_posts WHERE post_author = '10' AND ( post_status = 'published' OR post_status = 'donation' AND ID IN ('1','2','3'))

排序、分组、限制和偏移量

排序

QueryBuilder::orderBy方法允许您根据给定的列对查询结果进行排序。

DB::table('posts')->orderBy('ID');

生成的SQL

SELECT * FROM wp_posts ORDER BY ID ASC

按多列排序结果

DB::table('posts')
    ->orderBy('ID')
    ->orderBy('post_date', 'DESC');

生成的SQL

SELECT * FROM wp_posts ORDER BY ID ASC, post_date DESC

分组

QueryBuilder::groupByQueryBuilder::having*方法用于对查询结果进行分组。

可用方法 - groupBy / having / orHaving / havingCount / orHavingCount / havingMin / orHavingMin / havingMax / orHavingMax / havingAvg / orHavingAvg / havingSum / orHavingSum / havingRaw

DB::table('posts')
    ->groupBy('id')
    ->having('id', '>', 10);

生成的SQL

SELECT * FROM wp_posts WHERE GROUP BY id HAVING 'id' > '10'

限制和偏移量

限制查询返回的结果数量。

可用方法 - limit / offset

DB::table('posts')
    ->limit(10)
    ->offset(20);

生成的SQL

SELECT * FROM wp_posts LIMIT 10 OFFSET 20

处理元表的特殊方法

查询构建器有一组用于抽象与元表工作的特殊方法。

attachMeta

attachMeta用于将元表meta_key列的值包含在SELECT语句的列中。

在底层,QueryBuilder::attachMeta将为每个定义的meta_key列添加连接子句。每个列也将添加到选择语句中,这意味着元列将返回在查询结果中。在调用QueryBuilder::attachMeta方法时建议使用元列别名。

DB::table('posts')
    ->select(
        ['ID', 'id'],
        ['post_date', 'createdAt'],
        ['post_modified', 'updatedAt'],
        ['post_status', 'status'],
        ['post_parent', 'parentId']
    )
    ->attachMeta('give_donationmeta', 'ID', 'donation_id',
        ['_give_payment_total', 'amount'],
        ['_give_payment_currency', 'paymentCurrency'],
        ['_give_payment_gateway', 'paymentGateway'],
        ['_give_payment_donor_id', 'donorId'],
        ['_give_donor_billing_first_name', 'firstName'],
        ['_give_donor_billing_last_name', 'lastName'],
        ['_give_payment_donor_email', 'donorEmail'],
        ['subscription_id', 'subscriptionId']
    )
    ->leftJoin('give_donationmeta', 'ID', 'donationMeta.donation_id', 'donationMeta')
    ->where('post_type', 'give_payment')
    ->where('post_status', 'give_subscription')
    ->where('donationMeta.meta_key', 'subscription_id')
    ->where('donationMeta.meta_value', 1)
    ->orderBy('post_date', 'DESC');

生成的SQL

SELECT ID                                         AS id,
       post_date                                  AS createdAt,
       post_modified                              AS updatedAt,
       post_status                                AS status,
       post_parent                                AS parentId,
       give_donationmeta_attach_meta_0.meta_value AS amount,
       give_donationmeta_attach_meta_1.meta_value AS paymentCurrency,
       give_donationmeta_attach_meta_2.meta_value AS paymentGateway,
       give_donationmeta_attach_meta_3.meta_value AS donorId,
       give_donationmeta_attach_meta_4.meta_value AS firstName,
       give_donationmeta_attach_meta_5.meta_value AS lastName,
       give_donationmeta_attach_meta_6.meta_value AS donorEmail,
       give_donationmeta_attach_meta_7.meta_value AS subscriptionId
FROM wp_posts
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_0
                   ON ID = give_donationmeta_attach_meta_0.donation_id AND
                      give_donationmeta_attach_meta_0.meta_key = '_give_payment_total'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_1
                   ON ID = give_donationmeta_attach_meta_1.donation_id AND
                      give_donationmeta_attach_meta_1.meta_key = '_give_payment_currency'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_2
                   ON ID = give_donationmeta_attach_meta_2.donation_id AND
                      give_donationmeta_attach_meta_2.meta_key = '_give_payment_gateway'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_3
                   ON ID = give_donationmeta_attach_meta_3.donation_id AND
                      give_donationmeta_attach_meta_3.meta_key = '_give_payment_donor_id'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_4
                   ON ID = give_donationmeta_attach_meta_4.donation_id AND
                      give_donationmeta_attach_meta_4.meta_key = '_give_donor_billing_first_name'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_5
                   ON ID = give_donationmeta_attach_meta_5.donation_id AND
                      give_donationmeta_attach_meta_5.meta_key = '_give_donor_billing_last_name'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_6
                   ON ID = give_donationmeta_attach_meta_6.donation_id AND
                      give_donationmeta_attach_meta_6.meta_key = '_give_payment_donor_email'
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_7
                   ON ID = give_donationmeta_attach_meta_7.donation_id AND
                      give_donationmeta_attach_meta_7.meta_key = 'subscription_id'
         LEFT JOIN wp_give_donationmeta donationMeta ON ID = donationMeta.donation_id
WHERE post_type = 'give_payment'
  AND post_status = 'give_subscription'
  AND donationMeta.meta_key = 'subscription_id'
  AND donationMeta.meta_value = '1'
ORDER BY post_date DESC

返回结果

stdClass Object
(
    [id] => 93
    [createdAt] => 2022-02-21 00:00:00
    [updatedAt] => 2022-01-21 11:08:09
    [status] => give_subscription
    [parentId] => 92
    [amount] => 100.000000
    [paymentCurrency] => USD
    [paymentGateway] => manual
    [donorId] => 1
    [firstName] => Ante
    [lastName] => Laca
    [donorEmail] => dev-email@flywheel.local
    [subscriptionId] => 1
)

获取相同元键的多个实例

有时我们需要获取相同元键的多个实例。可以通过将第三个参数设置为true来实现,例如['additional_email', 'additionalEmails', true]

DB::table('give_donors')
  ->select(
      'id',
      'email',
      'name'
  )
  ->attachMeta(
      'give_donormeta',
      'id',
      'donor_id',
  	  ['additional_email', 'additionalEmails', true]
  );

生成的SQL

SELECT id, email, name, GROUP_CONCAT(DISTINCT give_donormeta_attach_meta_0.meta_value) AS additionalEmails
FROM wp_give_donors
    LEFT JOIN wp_give_donormeta give_donormeta_attach_meta_0 ON id = give_donormeta_attach_meta_0.donor_id AND give_donormeta_attach_meta_0.meta_key = 'additional_email'
GROUP BY id

返回结果

具有相同键的实例,在这种情况下为additional_email,将连接成JSON数组字符串。

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [email] => bill@flywheel.local
            [name] => Bill Murray
            [additionalEmails] => ["email1@lywheel.local","email2@lywheel.local"]
        )

    [1] => stdClass Object
        (
            [id] => 2
            [email] => jon@flywheel.local
            [name] => Jon Waldstein
            [additionalEmails] => ["email3@lywheel.local","email4@lywheel.local","email5@lywheel.local"]
        )

    [2] => stdClass Object
        (
            [id] => 3
            [email] => ante@flywheel.local
            [name] => Ante laca
            [additionalEmails] =>
        )

)

configureMetaTable

默认情况下,QueryBuilder::attachMeta将使用meta_keymeta_value作为元表列名,但有时可能并非如此。

使用QueryBuilder::configureMetaTable,您可以定义自定义的meta_keymeta_value列名。

DB::table('posts')
    ->select(
        ['ID', 'id'],
        ['post_date', 'createdAt']
    )
    ->configureMetaTable(
        'give_donationmeta',
        'custom_meta_key',
        'custom_meta_value'
    )
    ->attachMeta(
        'give_donationmeta',
        'ID',
        'donation_id',
        ['_give_payment_total', 'amount']
    )
    ->leftJoin('give_donationmeta', 'ID', 'donationMeta.donation_id', 'donationMeta')
    ->where('post_type', 'give_payment')
    ->where('post_status', 'give_subscription')
    ->where('donationMeta.custom_meta_key', 'subscription_id')
    ->where('donationMeta.custom_meta_value', 1);

生成的SQL

SELECT ID AS id, post_date AS createdAt, give_donationmeta_attach_meta_0.custom_meta_value AS amount
FROM wp_posts
         LEFT JOIN wp_give_donationmeta give_donationmeta_attach_meta_0
                   ON ID = give_donationmeta_attach_meta_0.donation_id AND
                      give_donationmeta_attach_meta_0.custom_meta_key = '_give_payment_total'
         LEFT JOIN wp_give_donationmeta donationMeta ON ID = donationMeta.donation_id
WHERE post_type = 'give_payment'
  AND post_status = 'give_subscription'
  AND donationMeta.custom_meta_key = 'subscription_id'
  AND donationMeta.custom_meta_value = '1'

CRUD

插入

QueryBuilder还提供了QueryBuilder::insert方法,可以用来将记录插入数据库表。

DB::table('posts')
    ->insert([
        'post_title'   => 'Post Title',
        'post_author'  => 1,
        'post_content' => 'Post Content'
    ]);

更新

除了将记录插入数据库之外,QueryBuilder还可以使用QueryBuilder::update方法更新现有记录。

DB::table('posts')
    ->where('post_author', 1)
    ->update([
        'post_title'   => 'Post Title 2',
        'post_content' => 'Post Content 2'
    ]);

Upsert

QueryBuilder::upsert方法可以用来更新现有记录或创建不存在的新记录。

// Would result in a new row - Oakland to San Diego for 100.
DB::table('table_name')
    ->upsert(
        ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => '100'] ,
        ['departure','destination']
    );


// Would update the row that was just inserted - Oakland to San Diego for 99.
DB::table('table_name')
    ->upsert(
        ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => '99'] ,
        ['departure','destination']
    );

删除

QueryBuilder::delete方法可以用来从表中删除记录。

DB::table('posts')
    ->where('post_author', 1)
    ->delete();

获取

可用方法 - get / getAll

获取单行

$post = DB::table('posts')->where('post_author', 1)->get();

获取所有行

$posts = DB::table('posts')->where('post_status', 'published')->getAll();

继承自 $wpdb

作为$wpdb的包装器,您可以使用$wpdb公开的所有方法。您只需在这样做时匹配$wpdb方法的签名即可。

尽管所有方法都受支持,但get_var()get_col()esc_like()remove_placeholder_escape()可能最有兴趣,因为库本身中没有等效的方法。

get_var()

获取给定查询的单个meta_value列。

$meta_value = DB::get_var(
	DB::table( 'postmeta' )
		->select( 'meta_value' )
		->where( 'post_id', 123 )
		->where( 'meta_key', 'some_key' )
		->getSQL()
);

get_col()

返回给定查询的列值的数组。

$meta_values = DB::get_col(
	DB::table( 'postmeta' )
		->select( 'meta_value' )
		->where( 'meta_key', 'some_key' )
		->getSQL()
);

esc_like()

转义包含百分号的字符串,以便可以安全地用于Where LIKE,而不会将百分号解释为通配符。

$escaped_string = DB::esc_like( 'This string has a % in it that is not a wildcard character' );

$results = DB::table( 'posts' )
    ->whereLike( 'post_content', "%{$escaped_string}%" )
    ->getAll();

remove_placeholder_escape()

从SQL查询中删除占位符转义字符串。

$wpdb生成类似于{abb19424319f69be9475708db0d2cbb780cb2dc2375bcb2657c701709ff71a9f}的占位符,当生成SQL查询时,它将使用转义字符%。这个库作为$wpdb的包装器,也会这样做。

使用DB::remove_placeholder_escape()会将这些转义字符替换回%,这在需要以更人性化的格式显示查询时可能很有用。

$escaped_sql = DB::table( 'postmeta' )
	->whereLike( 'meta_key', '%search string%' )
	->getSql();

$sql = DB::remove_placeholder_escape( $escaped_sql );

聚合函数

QueryBuilder还提供了一系列用于检索聚合值的方法,如countsumavgminmax

Count

$count = DB::table('posts')
    ->where('post_type', 'published')
    ->count();

计数非null列的行数。

$count = DB::table('donations')->count('not_null_value_column');

Sum

$sum = DB::table('give_donationmeta')
    ->where('meta_key', 'donation_amount')
    ->sum('meta_value');

Avg

$avg = DB::table('give_donationmeta')
    ->where('meta_key', 'donation_amount')
    ->avg('meta_value');

Min

$min = DB::table('give_donationmeta')
    ->where('meta_key', 'donation_amount')
    ->min('meta_value');

Max

$max = DB::table('give_donationmeta')
    ->where('meta_key', 'donation_amount')
    ->max('meta_value');

致谢

感谢GiveWP团队创建这个库!