php - 多个字段的 Laravel SUM 使用原始查询返回 null

标签 php mysql database laravel-5 eloquent

以下是我的查询:

 $sales = DB::table('sales')
        ->leftJoin('category_sales', 'category_sales.sale_id', '=', 'sales.id')
        ->leftJoin('department_sales', 'department_sales.sale_id', '=', 'sales.id')
        ->leftJoin('store_configs', 'store_configs.id', '=', 'sales.store_config_id')
        ->select('sales.date',
            DB::raw('store_configs.store_dba'),
            DB::raw('sales.id'),
            DB::raw('(sales.taxable + sales.non_taxable + category_sales.amount + department_sales.amount) as total_sales'),
            DB::raw('0.0825*(sales.taxable + category_sales.amount + department_sales.amount) as total_tax'))
        ->groupBy('date')->orderBy('date', 'desc')
        ->get();

当我在 category_sales 和 department_sales 表中有值时,我得到了正确的值。比方说,我没有任何 category_sales 中 sales_id 的金额值 表,total_salestotal_tax 的最终结果为空。

我的问题是:如果数据存在,我仍将如何对字段的值求和?

taxable, non_taxable, and amount'

category_sales 和 department_sales 中 是 defaults0

的整数

我的表结构只是一个想法,与 department_sales 类似:

CREATE TABLE `category_sales` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`amount` int(11) NOT NULL DEFAULT '0',
`category_id` int(10) unsigned DEFAULT NULL,
`sale_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `category_sales_category_id_index` (`category_id`),
KEY `category_sales_sale_id_index` (`sale_id`),
CONSTRAINT `category_sales_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
CONSTRAINT `category_sales_sale_id_foreign` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`id`) ON DELETE CASCADE) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

最佳答案

您可以将可为空的字段包装到 IFNULL() 函数中,如下所示:

DB::raw('(IFNULL(sales.taxable,0)
 + IFNULL(sales.non_taxable,0)
 + IFNULL(category_sales.amount,0)
 + IFNULL(department_sales.amount,0)
) as total_sales'),
DB::raw('0.0825*(IFNULL(sales.taxable,0) 
 + IFNULL(category_sales.amount,0)
 + IFNULL(department_sales.amount,0)) as total_tax'))

关于php - 多个字段的 Laravel SUM 使用原始查询返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768329/

相关文章:

android - 在sqlite中插入时获取主键而不是rowID或通过其rowID获取主键

java - JUNIT : run setup only once for a large number of test classes

php - 使用php从数据库上传和显示图片库

php - 如何防止 Wordpress 在摘录中剥离 HTML 标签

mysql - 当我尝试按用户 ID 查找数据时,dd() 返回 null

python - TypeError : tuple indices must be integers, not str

php - datepicker codeigniter 2.2问题

php - javascript或php数组交差法

mysql - 使用函数优化 mySQL 查询

php - 使用 CSV 和 MySQL 时的最小公分母