laravelÇóijһÁÐsum
laravelÊÇÏÖÔÚ×îÊ¢ÐеÄphp¿ò¼ÜÖ®Ò»£¬ËüÌṩÁËÐí¶à±ã½ÝµÄÒªÁ죬¿ÉÒÔÉÁ¿ª·¢Ö°Ô±Ô½·¢¸ßЧµØÍê³ÉʹÃü¡£ÆäÖÐÒ»¸ö³£ÓõĹ¦Ð§ÊǶÔÊý¾Ý¿âÖеÄÊý¾Ý¾ÙÐÐÇóºÍ²Ù×÷¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«Ì½ÌÖÔõÑùʹÓÃlaravel¶Ôijһö¾ÙÐÐÇóºÍ¡£
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent¾ÙÐÐÊý¾Ý¿â²Ù×÷¡£EloquentÊÇLaravelµÄORM£¨¹¤¾ß¹ØϵӳÉ䣩ģ¿é£¬¿ÉÒÔ½«Êý¾Ý¿â±í¸ñÓ³ÉäΪ¹¤¾ßÄ£×Ó£¬Àû±ãÎÒÃǾÙÐвÙ×÷¡£Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚLaravelÖнç˵һ¸öEloquentÄ£×Ó£¬ÓÃÓÚÓ³ÉäÎÒÃÇÒª²Ù×÷µÄ±í¸ñ¡£¼ÙÉèÎÒÃÇÒª¶Ô±í¸ñÖеÄijһÁС°amount¡±¾ÙÐÐÇóºÍ£¬½ç˵ģ×Ó´úÂëÈçÏ£º
namespace App; use IlluminateDatabaseEloquentModel; class Transaction extends Model { protected $table = 'transactions'; protected $fillable = ['amount', 'description']; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪ¡°Transaction¡±µÄÄ£×Ó£¬Ëü¶ÔÓ¦µÄÊý¾Ý¿â±í¸ñÃûΪ¡°transactions¡±¡£ÎÒÃÇÔÚfillableÊôÐÔÖнç˵Á˱í¸ñÖпɱ»ÅúÁ¿¸³ÖµµÄ×ֶΣ¬ÕâÀï°üÀ¨¡°amount¡±ºÍ¡°description¡±¡£
½ÓÏÂÀ´£¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquentÌṩµÄÒªÁì¶Ô¡°amount¡±Ã¶¾ÙÐÐÇóºÍ¡£ÎÒÃÇ¿ÉÒÔÔÚ¿ØÖÆÆ÷ÖбàдÈçÏ´úÂ룺
namespace AppHttpControllers; use AppTransaction; use IlluminateHttpRequest; class TransactionController extends Controller { public function totalAmount() { $sum = Transaction::sum('amount'); return view('transactions.total_amount', compact('sum')); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃLaravelµÄÒÀÀµ×¢È빦ЧÒýÈëÁËRequestÀàºÍTransactionÄ£×Ó¡£È»ºó£¬ÎÒÃDZàдÁËÒ»¸öÃûΪ¡°totalAmount¡±µÄÒªÁ죬Ëüͨ¹ýŲÓÃTransactionÄ£×ÓµÄsumÒªÁìÀ´¶Ô¡°amount¡±Ã¶¾ÙÐÐÇóºÍ¡£×îºó£¬ÎÒÃǽ«ÇóºÍЧ¹ûת´ï¸øÊÓͼÎļþ¡°transactions.total_amount¡±¾ÙÐÐչʾ¡£
×îºó£¬ÎÒÃÇÐèÒªÔÚ·ÓÉÎļþÖнç˵һ¸ö·ÓÉ£¬ÓÃÓÚ»á¼ûÕâ¸öÒªÁì¡£¼ÙÉèÎÒÃÇÒª½«¸ÃÒªÁì°ó¶¨µ½Â·ÓÉ¡°/transactions/total-amount¡±£¬Ôò¿ÉÒÔÔÚroutes/web.phpÖÐÌí¼ÓÈçÏ´úÂ룺
Route::get('/transactions/total-amount', 'TransactionController@totalAmount');
µÇ¼ºó¸´ÖÆ
ÏÖÔÚ£¬ÎÒÃÇÔÚä¯ÀÀÆ÷Öлá¼ûÍøÖ·¡°http://yourdomain.com/transactions/total-amount¡±£¬¼´¿ÉÉó²é¡°amount¡±ÁеÄ×ܺ͡£
×ܽáһϣ¬LaravelÌṩÁ˺ÜÊÇÀû±ãµÄ·½·¨À´¶ÔÊý¾Ý¿âÖеÄÊý¾Ý¾ÙÐÐÇóºÍ²Ù×÷¡£ÎÒÃÇÖ»ÐèҪʹÓÃEloquentÄ£×ÓµÄsumÒªÁì¼´¿ÉÇáËɵØʵÏÖ¡£
ÒÔÉϾÍÊÇlaravelÇóijһÁÐsumµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡