Laravel·Ö×éÅÌÎÊÇ°¼¸Ìõ¼Í¼
ÔÚlaravelÖУ¬ÎÒÃÇʱ³£ÐèÒª´ÓÊý¾Ý¿âÖÐÅÌÎÊÇ°¼¸Ìõ¼Í¼£¬ÀýÈçÅÌÎÊÒ»¸öÉÌÆ··ÖÀàÏÂÏúÁ¿Ç°ÎåµÄÉÌÆ·¡£ÕâÖÖÇéÐÎÏ£¬ÎÒÃÇͨ³£»áʹÓ÷Ö×éÅÌÎÊÀ´ÊµÏÖ¡£
±¾ÎĽ«ÏÈÈÝÔõÑùÔÚLaravelÖоÙÐзÖ×éÅÌÎÊ£¬²¢ÅÌÎÊÿ×éµÄÇ°¼¸Ìõ¼Í¼¡£
×¼±¸ÊÂÇé
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÓÐÒ»¸öÊý¾Ý±íÀ´´æ´¢ÉÌÆ·ÐÅÏ¢¡£¼ÙÉèÎÒÃÇÒѾ½¨ÉèÁËÒ»¸öÃûΪ¡°products¡±µÄÊý¾Ý±í£¬²¢²åÈëÁËһЩÊý¾Ý¡£
±àдÅÌÎÊÓï¾ä
ÎÒÃÇ¿ÉÒÔʹÓÃLaravelµÄÅÌÎʹ¹½¨Æ÷À´±àдÅÌÎÊÓï¾ä¡£Ê×ÏÈ£¬ÎÒÃÇÐèÒª¶ÔÉÌÆ·°´·ÖÀà¾ÙÐзÖ×飬ȻºóÔÙÅÌÎÊÿ×éµÄÇ°Îå¸öÉÌÆ·¡£ÅÌÎÊÓï¾äÈçÏ£º
$products = DB::table('products') ->select('category', DB::raw('MAX(sales) as max_sales')) ->groupBy('category') ->orderByDesc('max_sales') ->limit(5) ->get();
µÇ¼ºó¸´ÖÆ
ÕâÀïÎÒÃÇʹÓÃÁËselect()ÒªÁìÀ´Ö¸¶¨ÒªÅÌÎʵÄ×ֶΣ¬Í¬Ê±Ê¹ÓÃÁËDB::raw()ÒªÁìÀ´ÅÌËãÿ×éµÄ×î´óÏúÁ¿¡£groupBy()ÒªÁìÖ¸¶¨°´·ÖÀà×ֶξÙÐзÖ×飬orderByDesc()ÒªÁì°´×î´óÏúÁ¿½µÐòÅÅÐò£¬limit()ÒªÁìÏÞÖÆÅÌÎʵļͼÊýΪ5Ìõ¡£×îºó£¬Ê¹ÓÃget()ÒªÁìÖ´ÐÐÅÌÎÊ£¬²¢·µ»ØÒ»¸öÒÔ·ÖÀàΪ¼ü£¬ÒÔ×î´óÏúÁ¿ÎªÖµµÄЧ¹ûÜöÝÍ¡£
´¦ÀíÅÌÎÊЧ¹û
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª¶ÔÅÌÎÊЧ¹û¾ÙÐд¦Àí£¬ÒÔ»ñȡÿ×éµÄÇ°Îå¸öÉÌÆ·¡£ÎÒÃÇ¿ÉÒÔÔÚÒ»¸öÑ»·ÖжÔЧ¹ûÜöÝ;ÙÐд¦Àí£¬ÅÌÎÊÿ×éÖеÄÇ°Îå¸öÉÌÆ·£¬²¢½«ËüÃÇÌí¼Óµ½Ò»¸öеÄÊý×éÖС£
$result = []; foreach ($products as $product) { $query = DB::table('products') ->select('*') ->where('category', $product->category) ->orderByDesc('sales') ->limit(5) ->get(); $result[$product->category] = $query; }
µÇ¼ºó¸´ÖÆ
ÔÚÑ»·ÄÚ²¿£¬ÎÒÃÇÏÈÅÌÎÊÿ¸ö·ÖÀàϵÄËùÓÐÉÌÆ·£¬È»ºó°´ÏúÁ¿½µÐòÅÅÐò£¬ÏÞÖÆÅÌÎʼͼÊýΪ5£¬×îºó½«ÅÌÎÊЧ¹ûÌí¼Óµ½ÐÂÊý×éÖС£Ñ»·¿¢Êºó£¬ÎÒÃǾͻñµÃÁËÒ»¸öÒÔ·ÖÀàΪ¼ü£¬ÒÔÅÌÎÊЧ¹ûΪֵµÄÐÂÊý×飬¸ÃÊý×é°üÀ¨ÁËÿ¸ö·ÖÀàÖÐÏúÁ¿Ç°ÎåµÄÉÌÆ·¡£
Êä³öЧ¹û
×îºó£¬ÎÒÃÇ¿ÉÒÔ±éÀúÐÂÊý×飬½«ÅÌÎÊЧ¹ûÊä³öµ½Ò³ÃæÖС£
foreach ($result as $category => $products) { echo '<h3>'.$category.'</h3>'; echo '<ul>'; foreach ($products as $product) { echo '<li>' . $product->name . '</li>'; } echo '</ul>'; }
µÇ¼ºó¸´ÖÆ
ÔÚÊä³öЧ¹ûʱ£¬ÎÒÃÇÏÈÊä³ö·ÖÀàµÄÃû³Æ£¬È»ºóÔÚÒ»¸öulÁбíÖÐÊä³öÿ¸öÉÌÆ·µÄÃû³Æ¡£
×ܽá
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùÔÚLaravelÖÐʹÓ÷Ö×éÅÌÎÊÀ´ÅÌÎÊÿ×éµÄÇ°¼¸Ìõ¼Í¼¡£Í¨¹ýʹÓÃselect()¡¢groupBy()¡¢orderByDesc()¡¢limit()µÈÒªÁ죬ÎÒÃÇ¿ÉÒÔÎÞаµØ±àдÅÌÎÊÓï¾ä£¬ÊµÏÖÖÖÖÖÖØ´óµÄÅÌÎÊÐèÇó¡£Í¬Ê±£¬ÎÒÃÇҲѧϰÁËÔõÑùʹÓÃLaravelµÄÅÌÎʹ¹½¨Æ÷À´±àдÊý¾Ý¿âÅÌÎÊÓï¾ä£¬²¢¶ÔÅÌÎÊЧ¹û¾ÙÐд¦ÀíºÍÊä³ö¡£
ÒÔÉϾÍÊÇLaravel·Ö×éÅÌÎÊÇ°¼¸Ìõ¼Í¼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡