withÓ÷¨laravel
Ëæ×Ålaravel³ÉΪphp¿ª·¢ÖÐ×îÊܽӴýµÄ¿ò¼ÜÖ®Ò»£¬Ô½À´Ô½¶àµÄ¿ª·¢Õß×îÏÈʹÓÃËüÀ´¹¹½¨¸ßÐÔÄÜ¡¢¿ÉÀ©Õ¹µÄwebÓ¦ÓóÌÐò¡£ÔÚlaravelÖУ¬Ê¹Óá°with¡±ÒªÁì¿ÉÒÔÇáËɵؾÙÐжà´ÎÊý¾Ý¿âÅÌÎÊ£¬Õâ¿ÉÒÔÓÐÓõØÌá¸ßÐÔÄܺÍïÔÌÅÌÎÊʱ¼ä¡£±¾ÎĽ«ÏÈÈÝlaravelÖеġ°with¡±ÒªÁìµÄÓ÷¨¼°ÆäÓÅÊÆ¡£
Ò»¡¢Ê²Ã´ÊÇ¡°with¡±ÒªÁì
ÔÚLaravelÖУ¬Ê¹Óá°with¡±ÒªÁì¿ÉÒÔÇáËɵؽâ¾ö¡°N+1ÅÌÎÊ¡±ÎÊÌ⣬¼´µ±ÄãÏëÅÌÎÊÒ»¸öÄ£×Ó¼°Æä¹ØÁªÄ£×Óʱ£¬ÈôÊÇÄãʹÓÃÁËÑ»·ÅÌÎÊ£¬ÄÇô¾Í»á±¬·¢´ó×ÚµÄÅÌÎÊÓï¾ä£¬´Ó¶øµ¼ÖÂÐÔÄÜϽµ¡£Ê¹Óá°with¡±ÒªÁ죬¿ÉÒÔÈÃLaravelÒ»´ÎÅÌÎʳöËùÓйØÁªÄ£×ÓµÄÊý¾Ý£¬Õ⽫´ó´óÌá¸ßÐÔÄܺÍïÔÌÅÌÎÊʱ¼ä¡£
¶þ¡¢¡°with¡±ÒªÁìµÄÓ÷¨
¡°with¡±ÒªÁì¿ÉÒÔÔÚÅÌÎÊÆ÷ÖÐʹÓã¬Ò²¿ÉÒÔÔÚÄ£×ÓÖÐʹÓá£ÎÒÃÇÏÈÀ´¿´¿´ÔÚÅÌÎÊÆ÷ÖÐʹÓá°with¡±ÒªÁìµÄÓï·¨£º
User::with('posts')->get();
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂë¿ÉÒÔÃ÷ȷΪ£º¡°ÅÌÎÊÓû§£¬²¢Ò»ÆðÅÌÎÊÿ¸öÓû§µÄËùÓÐÎÄÕ¡±¡£Õâ¶Î´úÂëÏÖʵÉÏÖ»Ö´ÐÐÁËÁ½¸öÅÌÎÊ£¬¼´Ò»´ÎÅÌÎÊÓû§ÒÔ¼°ËùÓÐÓû§¹ØÁªµÄÎÄÕ£¬¶ø²»ÊÇÿ¸öÓû§¶¼¾ÙÐÐÒ»´ÎÅÌÎÊ¡£
³ýÁ˼òÆӵĹØÁª£¬»¹¿ÉÒÔͨ¹ýת´ïÒ»¸öÄäÃûº¯ÊýÀ´¹ýÂËÅÌÎÊ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÖ»ÅÌÎÊÓû§ÔÚ×î½üÒ»ÖÜÄÚÐû²¼µÄÎÄÕ£º
User::with(['posts' => function($query) { $query->where('created_at', '>=', Carbon::now()->subWeek()); }])->get();
µÇ¼ºó¸´ÖÆ
ͨ¹ýʹÓÃÄäÃûº¯Êý£¬ÎÒÃÇ¿ÉÒÔÖ¸¶¨Ìض¨Ä£×ӵĹØϵºÍ¹ýÂËÆ÷£¬²¢ÇÒ¿ÉÒÔƾ֤ÐèÒªÁ´Ê½Å²Óöà¸ö¹ØÁª¡£ÀýÈ磬ÔÚÒ»¸ö²©¿ÍÓ¦ÓóÌÐòÖУ¬ÎÒÃÇÏëÒªÅÌÎÊËùÓÐÎÄÕ¼°Æä×÷Õß¡¢Ì¸ÂÛÒÔ¼°Ì¸ÂÛµÄ×÷Õߣº
$posts = Post::with(['author', 'comments', 'comments.author'])->get();
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂëÅÌÎÊÁËËùÓÐÎÄÕ¼°Æä×÷Õß¡¢Ì¸ÂÛºÍ̸ÂÛµÄ×÷Õߣ¬Ö»Ö´ÐÐÁË3¸öÅÌÎÊ£¬¶ø²»ÊÇÿ´ÎÖ´ÐÐÒ»¸öÅÌÎÊ¡£Õ⽫´ó´óÌá¸ßÐÔÄܺÍïÔÌÅÌÎÊʱ¼ä¡£
Èý¡¢¡°with¡±ÒªÁìµÄÓÅÊÆ
ʹÓá°with¡±ÒªÁìµÄÓÅÊÆÔÚÓÚËü¿ÉÒÔïÔÌÊý¾Ý¿âÅÌÎÊ´ÎÊý£¬Ìá¸ßÐÔÄܺÍïÔÌÅÌÎÊʱ¼ä¡£µ±ÄãÐèÒªÅÌÎʶà¸ö¹ØÁªÄ£×Óʱ£¬Í¨¹ýʹÓá°with¡±ÒªÁ죬Äã¿ÉÒÔÖ»Ö´ÐÐÒ»´ÎÅÌÎÊ£¬¶ø²»ÊÇΪÿ¸öÄ£×Óµ¥¶ÀÖ´ÐÐÒ»´ÎÅÌÎÊ¡£Õ⽫ïÔÌÊý¾Ý¿âÇëÇ󣬴ӶøÌá¸ßÐÔÄÜ¡£
ͬʱ£¬LaravelµÄ¡°with¡±ÒªÁìÄܹ»Í¨¹ýת´ïÄäÃûº¯ÊýÀ´¹ýÂËÅÌÎÊ£¬´Ó¶ø½øÒ»²½ÓÅ»¯ÅÌÎÊ¡£ÕâÒâζ×ÅÄã¿ÉÒÔƾ֤ÐèÒª½«¹ØϵºÍ¹ýÂËÆ÷Á´½ÓÔÚÒ»Æ𣬲¢ÇÒ¿ÉÒÔÎÞаµØ¾ÙÐÐÅÌÎÊ£¬²¢»ñµÃ׼ȷµÄЧ¹û¡£
ËÄ¡¢×ܽá
LaravelµÄ¡°with¡±ÒªÁìÊÇÒ»ÖÖÓÅ»¯Êý¾Ý¿âÅÌÎʵÄÇ¿Ê¢¹¤¾ß£¬¿ÉÒÔïÔÌÊý¾Ý¿âÅÌÎÊ´ÎÊý£¬Ìá¸ßÐÔÄܺÍïÔÌÅÌÎÊʱ¼ä¡£Óëµ¥¶ÀÅÌÎÊÿ¸ö¹ØÁªÄ£×ÓÏà±È£¬Ê¹Óá°with¡±ÒªÁì¿ÉÒÔ¸üºÃµØÖÎÀíºÍ´¦ÀíÏà¹ØÊý¾Ý£¬Ìá¸ßWebÓ¦ÓóÌÐòµÄÐÔÄܺͿÉÉìËõÐÔ¡£ÈôÊÇÄãÕýÔÚʹÓÃLaravel¹¹½¨WebÓ¦ÓóÌÐò£¬ÄÇô¡°with¡±ÒªÁ콫ÊÇÌá¸ßÅÌÎÊÐÔÄܵÄÖ÷Òª¹¤¾ßÖ®Ò»¡£
ÒÔÉϾÍÊÇwithÓ÷¨laravelµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡