laravel¶à±íÅÌÎÊÅÅÐò
Ëæ×Å»¥ÁªÍøÊÖÒÕµÄÉú³¤£¬webÓ¦ÓóÌÐòµÄÐèÇóÔ½À´Ô½ÖØ´ó£¬Éæ¼°µ½¶à¸öÊý¾Ý±íµÄ¹ØÁªÅÌÎʺÍÅÅÐò¡£×÷Ϊһ¿î¸ßЧ¡¢ÎÞаµÄ php ¿ªÔ´¿ò¼Ü£¬laravel ÌṩÁËÐí¶àÀû±ãµÄÒªÁìÀ´ÖÎÀíºÍÅÌÎʶà¸öÊý¾Ý±í¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓà laravel ¾ÙÐжà±íÅÌÎʺÍÅÅÐò¡£
¶à±íÅÌÎÊ
ÔÚ Laravel ÖУ¬Ê¹Óà Eloquent ORM ¿ÉÒÔÇáËÉʵÏÖ¶à±íÅÌÎÊ¡£ Eloquent ÊÇÒ»¸öÇ¿Ê¢µÄ ORM£¬¿ÉÒÔ½«Êý¾Ý¿â±íÓ³Éäµ½ PHP ¹¤¾ß£¬²¢ÌṩÁ˶àÖÖÅÌÎÊÒªÁì¡£
ÀýÈ磬¼ÙÉèÎÒÃÇÓÐÁ½¸ö±í£ºusers£¨Óû§£©ºÍposts£¨ÎÄÕ£©£¬ÆäÖÐÎÄÕ±íÖÐÓÐÒ»¸öÍâ¼ü user_id ´æ´¢ÁËÐû²¼¸ÃÎÄÕµÄÓû§ id¡£ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔÏ·½·¨À´ÅÌÎÊÒ»¸öÓû§Ðû²¼µÄËùÓÐÎÄÕ£º
$user = User::find(1); $posts = $user->posts;
µÇ¼ºó¸´ÖÆ
ÕâÀïÊ×ÏÈͨ¹ý User Ä£× find ÒªÁì»ñÈ¡¶ÔÓ¦ ID µÄÓû§¹¤¾ß£¬È»ºóͨ¹ý»á¼û $user->posts ÊôÐÔÀ´»ñÈ¡¸ÃÓû§Ðû²¼µÄËùÓÐÎÄÕ¡£ ÕâÖÖ·½·¨ÏÖʵÉÏÊÇ Eloquent µÄÒ»ÖÖ¹Øϵ£¬ÔÚ User Ä£×ÓÖнç˵ÁËÒ»¸ö½Ð×ö posts µÄÒªÁ죬¸ÃÒªÁì½ç˵ÁË User Ä£×ÓºÍ Post Ä£×ÓÖ®¼äµÄ¹Øϵ¡£
»¹¿ÉÒÔʹÓà with ÒªÁì¾ÙÐÐÔ¤¼ÓÔØ£¬×èÖ¹ÔÚ±éÀúÓû§Ê±Ö´Ðжà¸öÅÌÎÊ£¬Ìá¸ßÅÌÎÊЧÂÊ£º
$users = User::with('posts')->get(); foreach ($users as $user) { $posts = $user->posts; }
µÇ¼ºó¸´ÖÆ
ÕâÀïʹÓà with ÒªÁìÔ¤¼ÓÔØÁËËùÓÐÓû§µÄËùÓÐÎÄÕ£¬È»ºóÔÚÑ»·Öлá¼û $user->posts ÊôÐÔ£¬¿ÉÒÔ×èÖ¹ÔÚÑ»·ÖÐÖ´Ðжà¸öÅÌÎÊ¡£
³ýÁË Eloquent ÌṩµÄÄ£×Ó¹Øϵ£¬»¹¿ÉÒÔʹÓà join ÒªÁìÀ´Ö´ÐÐÖØ´óµÄ¶à±íÅÌÎÊ¡£ÀýÈ磬ÒÔÏ´úÂ뽫ÅÌÎÊÿƪÎÄÕ¶ÔÓ¦µÄ×÷ÕߺÍ̸ÂÛÊý£º
$posts = DB::table('posts') ->join('users', 'posts.user_id', '=', 'users.id') ->leftJoin('comments', 'posts.id', '=', 'comments.post_id') ->select('posts.*', 'users.name', DB::raw('count(comments.id) as comments_count')) ->groupBy('posts.id') ->get();
µÇ¼ºó¸´ÖÆ
ÕâÀïʹÓÃÁË join ºÍ leftJoin ÒªÁìÀ´ÅþÁ¬Èý¸ö±í£¬È»ºóʹÓà select ÒªÁìÑ¡ÕªÒªÅÌÎʵÄ×ֶΣ¬ÆäÖÐʹÓÃÁË DB::raw ÒªÁìÀ´ÌìÉúÔʼÅÌÎÊÓï¾äÖÐµÄ count(comments.id) ²¿·Ö¡£×îºóʹÓà groupBy ÒªÁì¶ÔÎÄÕ¾ÙÐзÖ×é¡£
¶à±íÅÅÐò
ÔÚ¶à±íÅÌÎʵĻù´¡ÉÏ£¬ÎÒÃÇ¿ÉÄÜÐèÒª¶ÔÅÌÎÊЧ¹û¾ÙÐÐÅÅÐò¡£ Laravel ÌṩÁ˶àÖÖÅÅÐò·½·¨À´Öª×ã²î±ðÐèÇó¡£
2.1 µ¥±íÅÅÐò
¹ØÓÚµ¥±íÅÅÐò£¬Laravel ÌṩÁË orderBy ÒªÁ죬¿ÉÒÔƾָ֤¶¨µÄ×Ö¶ÎÅÅÐò£¬ÀýÈ磺
$users = User::orderBy('name', 'desc')->get();
µÇ¼ºó¸´ÖÆ
ÕâÀïƾ֤ name ×ֶνµÐòÅÅÐòËùÓÐÓû§¡£
2.2 ¹ØÁª±íÅÅÐò
¹ØÓÚ¹ØÁª±íÅÅÐò£¬¿ÉÒÔÔÚ¹ØÁªÒªÁìÖнç˵ orderBy£¬ÀýÈ磺
class User extends Model { public function posts() { return $this->hasMany(Post::class)->orderBy('created_at', 'desc'); } }
µÇ¼ºó¸´ÖÆ
ÕâÀïÔÚ User Ä£× posts ÒªÁìÖнç˵ÁË orderBy£¬Ã¿´ÎŲÓà $user->posts ʱ£¬¶¼»áƾ֤ created_at ×ֶνµÐòÅÅÐòÎÄÕ¡£
2.3 ¶à±íÅÅÐò
¹ØÓÚ¶à±íÅÅÐò£¬ÎÒÃÇ¿ÉÒÔʹÓà join ºÍ orderBy ÒªÁ죬ÀýÈ磺
$posts = DB::table('posts') ->join('users', 'posts.user_id', '=', 'users.id') ->orderBy('users.name', 'desc') ->orderBy('posts.created_at', 'desc') ->get();
µÇ¼ºó¸´ÖÆ
ÕâÀïƾ֤Óû§µÄ name ×ֶνµÐòÅÅÐò£¬È»ºóƾ֤ÎÄÕ嵀 created_at ×ֶνµÐòÅÅÐò¡£
×ܽá
Laravel ÌṩÁ˶àÖÖÀû±ãµÄÒªÁìÀ´ÅÌÎʺÍÅÅÐò¶à¸öÊý¾Ý±í£¬°üÀ¨ Eloquent Ä£×Ó¹Øϵ¡¢join ÒªÁì¡¢orderBy ÒªÁìµÈ¡£ÔÚÏÖʵ¿ª·¢ÖУ¬Æ¾Ö¤ÏêϸÐèÇóÑ¡Ôñ²î±ðµÄÒªÁì¾ÙÐÐÅÌÎʺÍÅÅÐò£¬¿ÉÒÔÌá¸ßÅÌÎÊЧÂʺʹúÂ뾫Á·¶È¡£
ÒÔÉϾÍÊÇlaravel¶à±íÅÌÎÊÅÅÐòµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡