laravelÔõô¹¹½¨ÖØ´óÅÌÎÊÌõ¼þ
ÔÚlaravelÖУ¬¹¹½¨ÖØ´óÅÌÎÊÌõ¼þÊǺܳ£¼ûµÄÐèÇó¡£ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊͬʱ֪×ã¶à¸öÌõ¼þµÄÊý¾Ý£¬ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊij¸ö×Ö¶Î×î´óÖµ»ò×îСֵ£¬ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊijЩÌõ¼þ²»Öª×ãµÄÊý¾ÝµÈµÈ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃlaravelµÄÅÌÎʽṹÆ÷À´ÊµÏÖÕâЩÐèÇó¡£
»ù±¾ÅÌÎÊ
Ê×ÏÈ£¬ÎÒÃÇÀ´¿´Ò»ÏÂLaravelµÄ»ù±¾ÅÌÎÊÓï·¨¡£ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃDBÃÅÃæµÄtable()ÒªÁìÀ´Ö¸¶¨ÎÒÃÇÒªÅÌÎÊµÄ±í£¬È»ºóʹÓÃselect()ÒªÁìÖ¸¶¨ÎÒÃÇÐèÒªÅÌÎʵÄ×ֶΡ£
ÀýÈ磬ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐËùÓеļͼ£¬²¢·µ»ØÆäidºÍname×ֶΣº
DB::table('users')->select('id', 'name')->get();
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÒ²¿ÉÒÔʹÓÃwhere()ÒªÁìÀ´Ö¸¶¨ÅÌÎÊÌõ¼þ¡£ÀýÈ磬ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐÄêËê´óÓÚ18µÄ¼Í¼£º
DB::table('users')->where('age', '>', 18)->get();
µÇ¼ºó¸´ÖÆ
ÅÌÎÊÌõ¼þ×éºÏ
µ±ÎÒÃÇÐèҪͬʱ֪×ã¶à¸öÌõ¼þʱ£¬¿ÉÒÔʹÓÃwhere()ÒªÁìÀ´×éºÏÅÌÎÊÌõ¼þ¡£
ÀýÈ磬ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐͬʱ֪×ãÄêËê´óÓÚ18ÇÒÐÔ±ðΪÄеļͼ£º
DB::table('users')->where('age', '>', 18)->where('gender', 'male')->get();
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÒ²¿ÉÒÔʹÓÃorWhere()ÒªÁìÀ´Ö¸¶¨ÆäÖÐÒ»¸öÌõ¼þÖª×ã¼´¿É¡£
ÀýÈ磬ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐÄêËê´óÓÚ18»òÐÔ±ðΪÄеļͼ£º
DB::table('users')->where('age', '>', 18)->orWhere('gender', 'male')->get();
µÇ¼ºó¸´ÖÆ
ÈôÊÇÎÒÃÇÐèÒª¶àÖØÌõ¼þµÄ×éºÏ£¬ÎÒÃÇ¿ÉÒÔʹÓñհüÀ´ÊµÏÖ¡£
ÀýÈ磬ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐͬʱ֪×ãÄêËê´óÓÚ18ÇÒÐÔ±ðΪÄлòÕßÄêËê¼´ÊÇ18ÇÒÐÔ±ðΪŮµÄ¼Í¼£º
DB::table('users')->where(function($query) { $query->where('age', '>', 18) ->where('gender', 'male'); })->orWhere(function($query) { $query->where('age', '=', 18) ->where('gender', 'female'); })->get();
µÇ¼ºó¸´ÖÆ
Ä£ºýÅÌÎÊ
ÓÐʱ¼äÎÒÃÇÐèҪƾ֤ij¸ö×ֶεÄÒ»²¿·ÖÀ´ÅÌÎÊ¡£ÎÒÃÇ¿ÉÒÔʹÓÃlike()ÒªÁìºÍͨÅä·ûÀ´ÊµÏÖÄ£ºýÅÌÎÊ¡£ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐÃû×ÖÒÔ¡°J¡±¿ªÍ·µÄ¼Í¼£º
DB::table('users')->where('name', 'like', 'J%')->get();
µÇ¼ºó¸´ÖÆ
×î´óÖµºÍ×îСֵÅÌÎÊ
ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊij¸ö×ֶεÄ×î´óÖµ»ò×îСֵ¡£ÎÒÃÇ¿ÉÒÔʹÓÃmax()ºÍmin()ÒªÁìÀ´ÊµÏÖ¡£ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐage×ֶεÄ×î´óÖµºÍ×îСֵ£º
$maxAge = DB::table('users')->max('age'); $minAge = DB::table('users')->min('age');
µÇ¼ºó¸´ÖÆ
²»¼´ÊÇÅÌÎÊ
ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊij¸ö×ֶβ»¼´ÊÇij¸öÖµµÄ¼Í¼¡£ÎÒÃÇ¿ÉÒÔʹÓÃwhere()ÒªÁìºÍ·ûºÅÀ´ÊµÏÖ¡£ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐÐÔ±ð²»ÎªÄеļͼ£º
DB::table('users')->where('gender', '', 'male')->get();
µÇ¼ºó¸´ÖÆ
inºÍnot inÅÌÎÊ
ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊij¸ö×Ö¶ÎÔÚij¸öÖµÁбíÖеļͼ¡£ÎÒÃÇ¿ÉÒÔʹÓÃwhereIn()ÒªÁìºÍÖµÁбíÀ´ÊµÏÖ¡£ÏÂÃæ´úÂë»áÅÌÎÊusers±íÖÐage×ֶεÄֵΪ18¡¢19»ò20µÄ¼Í¼£º
DB::table('users')->whereIn('age', [18, 19, 20])->get();
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÒ²¿ÉÒÔʹÓÃwhereNotIn()ÒªÁìÀ´ÅÌÎʲ»ÔÚÖµÁбíÖеļͼ¡£
existsºÍnot existsÅÌÎÊ
ÓÐʱ¼äÎÒÃÇÐèÒªÅÌÎÊij¸öÌõ¼þ±£´æ»ò²»±£´æµÄ¼Í¼¡£ÎÒÃÇ¿ÉÒÔʹÓÃwhereExists()ºÍwhereNotExists()ÒªÁìÀ´ÊµÏÖ¡£ÏÂÃæ´úÂë»áÅÌÎÊorders±íÖб£´æ¶ÔÓ¦Óû§µÄ¼Í¼£º
DB::table('orders') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('users') ->whereRaw('users.id = orders.user_id'); }) ->get();
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÒ²¿ÉÒÔʹÓÃwhereNotExists()ÒªÁìÀ´ÅÌÎʲ»±£´æ¶ÔÓ¦Óû§µÄ¼Í¼¡£
µ½´Ë£¬ÎÒÃÇÏÈÈÝÁËLaravel¹¹½¨ÖØ´óÅÌÎÊÌõ¼þµÄ»ù±¾ÒªÁì¡£LaravelµÄÅÌÎʽṹÆ÷ÈÃÎÒÃÇÔÚ±àдÅÌÎÊÓï¾äʱ¸ü¼òÆÓ¡¢¸üÖ±¹Û£¬¶ø²»±Ø¹ý¶à˼Á¿SQLÓï·¨µÄϸ½Ú¡£ËäÈ»£¬ÒÔÉÏÖ»ÊÇÅÌÎÊÓï¾äµÄ±ùɽһ½Ç£¬LaravelµÄÅÌÎʽṹÆ÷ÉÐÓÐÐí¶à¸ß¼¶Ó÷¨ÆÚ´ýÎÒÃÇÈ¥¾ò¿Í¡£
ÒÔÉϾÍÊÇlaravelÔõô¹¹½¨ÖØ´óÅÌÎÊÌõ¼þµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡