laravel groupbyÍÉ»¯
laravel ÊÇÒ»¸öÊ¢ÐÐµÄ php ¿ò¼Ü£¬Ëü¼ò»¯ÁË¿ª·¢ÕßµÄÊÂÇéÁ÷³Ì²¢Ìá¸ßÁËÓ¦ÓóÌÐòµÄ¿Éά»¤ÐÔ¡£ÔÚ laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃȺ×麯Êý£¨groupby£©¾ÛºÏÊý¾Ý¡£
È»¶ø£¬ÓÐʱ¼äÔÚʹÓà Laravel µÄ GroupBy º¯Êýʱ£¬»á·ºÆðһЩ²»¿ÉÔ¤ÁϵÄÎÊÌâ¡£±¾ÎĽ«ÎªÄúÏêϸÏÈÈÝÕâЩÎÊÌâÒÔ¼°ÔõÑù½â¾öËüÃÇ¡£
GroupBy ÎÞ·¨°´Ô¤ÆÚ·Ö×é
ÔÚ Laravel ÖÐʹÓà GroupBy º¯Êýʱ£¬×î³£¼ûµÄÎÊÌâÖ®Ò»¾ÍÊÇÎÞ·¨Æ¾Ö¤Ô¤Æڵķ½·¨¶ÔÊý¾Ý¾ÙÐзÖ×é¡£Õâ¿ÉÄÜÊÇÓÉÓÚ¶à¸öÔµ¹ÊÔÓɵ¼Öµģ¬ÀýÈçʹÓùýʧµÄÁÐÃû¡¢ÁÐÃûµÄ¾Þϸд²»Æ¥ÅäµÈ¡£
ΪÏàʶ¾öÕâ¸öÎÊÌ⣬Äú¿ÉÒÔʵÑéÒÔϽâ¾ö¼Æ»®£º
1£©È·±£ÄúʹÓõÄÁÐÃûÓëÊý¾Ý¿â±í½á¹¹ÖеÄÁÐÃûÍêÈ«Ïàͬ¡£
2£©ÈôÊÇÄúʹÓõÄÁÐÃûÖаüÀ¨´óд×Öĸ£¬Ôò±ØÐ轫ÆäÓëÊý¾Ý¿â±í½á¹¹ÖеÄÁÐÃûÏàÆ¥Åä¡£
3£©ÊµÑéʹÓà Laravel µÄ raw º¯ÊýÀ´Ö´ÐÐ SQL ÅÌÎÊ¡£
ÀýÈ磬¼ÙÉèÄúÓÐÒ»¸ö user ±í£¬°üÀ¨ id¡¢name ºÍ email Èý¸öÁС£Òª°´µç×ÓÓʼþµØµã¶ÔÓû§¾ÙÐзÖ×飬Äú¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
$users = DB::table('users') ->select('email', DB::raw('count(*) as total')) ->groupBy('email') ->get();
µÇ¼ºó¸´ÖÆ
GroupBy ·µ»Ø¹ýʧµÄЧ¹û
ÁíÒ»¸ö³£¼ûµÄÎÊÌâÊÇ£¬µ±Ê¹Óà GroupBy º¯Êýʱ£¬Ëü·µ»Ø¹ýʧµÄЧ¹û¡£Õâ¿ÉÄÜÊÇÓÉÓÚ¶à¸öÔµ¹ÊÔÓɵ¼Öµģ¬ÀýÈçʹÓùýʧµÄÅÌÎÊÓï¾ä¡¢ÔÚ GroupBy º¯ÊýÖÐʹÓÃÁ˹ýʧµÄÁÐÃûµÈ¡£
ΪÏàʶ¾öÕâ¸öÎÊÌ⣬Äú¿ÉÒÔʵÑéÒÔϽâ¾ö¼Æ»®£º
1£©È·±£ÄúʹÓõÄÅÌÎÊÓï¾ä׼ȷÎÞÎó¡£
2£©¼ì²éÄúʹÓõÄÁÐÃûÊÇ·ñ׼ȷ¡£
3£©Ê¹Óà Laravel µÄµ÷ÊÔ¹¤¾ßÀ´ÆÊÎöÎÊÌâ²¢²éÕÒ¹ýʧ¡£
ÀýÈ磬¼ÙÉèÄúÒª½« orders ±íƾ֤Óû§ ID ºÍ¶©µ¥ ID ·Ö×飬²¢ÅÌËãÿ¸öÓû§µÄ¶©µ¥×ÜÊýºÍÿ¸ö¶©µ¥µÄÊýÄ¿¡£Äú¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
$order_counts = DB::table('orders') ->select('user_id', 'order_id', DB::raw('count(*) as total')) ->groupBy('user_id', 'order_id') ->get();
µÇ¼ºó¸´ÖÆ
Çë×¢ÖØ£¬ÉÏÊöÅÌÎÊÖУ¬ÎÒÃÇÔÚ GroupBy º¯ÊýÖÐʹÓÃÁËÁ½¸öÁÐÃû¡£ÕâÈ·±£ÁËÎÒÃÇƾ֤Óû§ ID ºÍ¶©µ¥ ID ½«Êý¾Ý·Ö×飬²¢ÅÌËãÿ¸öÓû§µÄ¶©µ¥×ÜÊý¡£
GroupBy º¯ÊýÖ´ÐлºÂý
ÁíÒ»¸ö³£¼ûµÄÎÊÌâÊÇ£¬ÔÚʹÓà GroupBy º¯Êýʱ£¬ÅÌÎÊ¿ÉÄÜÖ´ÐлºÂý¡£Õâ¿ÉÄÜÊÇÓÉÓÚÄúµÄÊý¾Ý¿âÖÐÓдó×ÚÊý¾Ý»òÄúµÄЧÀÍÆ÷ÉèÖÃȱ·¦¡£
ΪÏàʶ¾öÕâ¸öÎÊÌ⣬Äú¿ÉÒÔʵÑéÒÔϽâ¾ö¼Æ»®£º
1£©Ê¹ÓÃË÷ÒýÀ´¼ÓËÙÅÌÎÊËÙÂÊ¡£
2£©ÓÅ»¯Êý¾Ý¿âЧÀÍÆ÷µÄÉèÖá£
3£©ÊµÑéÆÊÎöÅÌÎÊÒÔïÔÌÊý¾ÝɨÃè¡£
ÀýÈ磬¼ÙÉèÄúÏëƾ֤Óû§ ID ºÍ¶©µ¥Ê±¼ä·Ö×飬²¢ÅÌËãÿ¸öÓû§µÄ¶©µ¥×ÜÊý¡£Äú¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
$orders = DB::table('orders') ->select('user_id', DB::raw('DATE(created_at) as order_date'), DB::raw('COUNT(*) as order_count')) ->groupBy('user_id', 'order_date') ->get();
µÇ¼ºó¸´ÖÆ
Çë×¢ÖØ£¬ÎÒÃÇÔÚÅÌÎÊÖÐʹÓÃÁË DATE º¯ÊýÀ´½ö°´ÈÕÆÚ£¨²»°üÀ¨Ê±¼ä£©¾ÙÐзÖ×é¡£Õ⽫ïÔÌÅÌÎÊɨÃèµÄÊý¾ÝÁ¿£¬´Ó¶ø¼ÓËÙÅÌÎÊËÙÂÊ¡£
×ܽá
ÔÚ Laravel ÖÐʹÓà GroupBy º¯Êýʱ£¬¿ÉÄÜ»áÓöµ½Ðí¶àÎÊÌâ¡£±¾ÎÄÏÈÈÝÁËһЩ³£¼ûµÄÎÊÌâÒÔ¼°ÔõÑù½â¾öËüÃÇ¡£ÎÞÂÛÄúÊÇÔÚ´¦Öóͷ£´óÐÍÏîÄ¿ÕÕ¾ÉСÎÒ˽¼ÒÏîÄ¿£¬Ö»ÒªÄúÄÜ׼ȷµØʹÓà GroupBy º¯Êý£¬Äú¾Í¿ÉÒÔÇáËɾۺÏÊý¾Ý²¢¼ÓËÙÅÌÎÊËÙÂÊ¡£
ÒÔÉϾÍÊÇlaravel groupbyÍÉ»¯µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡