laravel sumÇóºÍ
laravelÊÇÒ»¿î±¸ÊܽӴýµÄphp¿ò¼Ü£¬ÌṩÁËÐí¶àÀû±ã¿ª·¢µÄ¹¦Ð§¡£ÆäÖУ¬¾Í°üÀ¨¹ØÓÚÊý¾Ý¿âµÄÅÌÎʺͻã×ܹ¦Ð§¡£±¾Îľͽ«×ÅÖؽâ˵ÔõÑùʹÓÃlaravelÖеÄsumÒªÁìÍê³ÉÇóºÍ²Ù×÷¡£
Ò»¡¢¸ÅÊö
ÔÚÊý¾Ý´¦Öóͷ£ÖУ¬ÇóºÍ²Ù×÷ÊǷǾ³£¼ûµÄÐèÇ󡣺ñȣ¬ÎÒÃÇÐèҪͳ¼ÆÒ»×éÊý¾ÝÖеÄ×ܺͣ¬»òÕßijһÁеÄ×ܺͣ¬ÕâʱÎÒÃǾÍÐèҪʹÓõ½ÇóºÍ²Ù×÷¡£
ÔÚLaravelÖУ¬Ê¹ÓÃEloquent ORMÀ´»á¼ûÊý¾Ý¿â£¬¿ÉÒÔÖ±½ÓŲÓÃLaravelÌṩµÄsumº¯Êý¾ÙÐÐÇóºÍ²Ù×÷¡£
¶þ¡¢Ê¹ÓÃLaravelµÄsumÒªÁì
¼ÙÉèÎÒÃÇÓÐÒ»¸öorders±í£¬ÆäÖаüÀ¨ÒÔϼ¸¸ö×ֶΣº id, user_id, amount¡£
ÏÖÔÚ£¬ÎÒÃÇÐèÒª¶Ôamount×ֶξÙÐÐÇóºÍ²Ù×÷£¬¿ÉÒÔʹÓÃÈçÏ´úÂ룺
$totalAmount = DB::table('orders')->sum('amount');
µÇ¼ºó¸´ÖÆ
ÕâÀïÎÒÃÇʹÓÃÁËLaravelµÄDBÃÅÃæÀ´»á¼ûorders±í£¬²¢Å²ÓÃÁËsumÒªÁ죬´«ÈëÁË×Ö¶ÎÃûamount£¬×îºó»ñµÃÁË$totalAmount£¬ÌåÏָñíamount×ֶεÄ×ܺ͡£
³ýÁËÕû¸ö±íµÄÇóºÍ²Ù×÷£¬ÎÒÃÇ»¹¿ÉÒԶԸñí¾ÙÐзÖ×éÇóºÍ¡£ºÃ±È£¬ÎÒÃÇÐèҪͳ¼Æÿ¸öÓû§(user_id)µÄ¶©µ¥½ð¶î×ܺͣ¬¿ÉÒÔʹÓÃÈçÏ´úÂ룺
$sumByUser = DB::table('orders')->select('user_id', DB::raw('SUM(amount) as total'))->groupBy('user_id')->get();
µÇ¼ºó¸´ÖÆ
ÕâÀïÎÒÃÇʹÓÃÁËselectÒªÁ죬»ñÈ¡ÁËuser_idºÍamount×ֶΣ¬²¢Ê¹ÓÃÁËDBµÄrawÒªÁ죬½«SUMº¯Êý×÷ΪSQLÓï¾äµÄÒ»²¿·Ö£¬ÒÔ±ã»ñµÃ×ܺÍ×ܺ͡£Í¬Ê±Ò²Ê¹ÓÃÁËgroupByÒªÁ죬¶Ôuser_id¾ÙÐÐÁË·Ö×é¡£
×îºó»ñµÃµÄЧ¹û¾Û»áÊÇÒ»¸öÊý×飬Êý×éÖеÄÿһ¸öÔªËض¼°üÀ¨ÁËÒ»¸öÓû§µÄuser_id×ֶκ͸ÃÓû§¶©µ¥½ð¶î×ܺÍtotal×ֶΡ£
Èý¡¢¸öÐÔ»¯¶¨ÖÆ
ÔÚʹÓÃLaravelµÄsumÒªÁìµÄͬʱ£¬ÎÒÃÇ»¹¿ÉÒÔ¶ÔsqlÅÌÎÊÓï¾ä¾ÙÐиöÐÔ»¯¶¨ÖÆ£¬ÒÔ˳ӦԽ·¢ÖØ´óµÄÊý¾ÝÐèÇó¡£
ºÃ±È£¬ÎÒÃÇ¿ÉÒÔÔÚɸѡÌõ¼þÖÐÌí¼ÓһЩ×Ô½ç˵µÄÅжϣ¬À´¹ýÂ˲»ÐèÒª¼ÆÈëÇóºÍµÄÊý¾Ý£º
$totalAmount = DB::table('orders')->where('status', 1)->sum('amount');
µÇ¼ºó¸´ÖÆ
ÕâÀïÎÒÃÇÔÚÅÌÎÊ֮ǰÌí¼ÓÁËwhereÒªÁ죬Ìí¼ÓÁËÒ»¸östatus×ֶΣ¬ÌåÏÖÖ»ÅÌË㶩µ¥×´Ì¬Îª1µÄ¶©µ¥½ð¶î×ܺ͡£
ËÄ¡¢×ܽá
LaravelÌṩÁ˱ã½ÝµÄÇóºÍ²Ù×÷¹¦Ð§£¬Àû±ãÁË¿ª·¢Õ߶ÔÊý¾Ý¾ÙÐÐͳ¼Æ¼°ÆÊÎö¡£Í¨¹ý±¾ÎĵÄÏÈÈÝ£¬¶ÁÕßÒѾѧ»áÔõÑùʹÓÃLaravelµÄsumÒªÁìÀ´Íê³ÉÇóºÍ²Ù×÷£¬²¢ÇÒÏàʶµ½ÁËÔõÑù¶ÔsqlÅÌÎÊÓï¾ä¾ÙÐиöÐÔ»¯¶¨ÖÆ¡£ÕâЩ¹¦Ð§Îª¿ª·¢ÕßÌṩÁ˸ü´óµÄÎÞа¶È£¬Ê¹Êý¾Ý²Ù×÷±äµÃÔ½·¢¸ßЧºÍ±ã½Ý¡£
ÒÔÉϾÍÊÇlaravel sumÇóºÍµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡