laravelÅÌÎÊд¶à¸öÌõ¼þ
ÔÚlaravelÖУ¬ÎÒÃǾ³£ÐèҪƾ֤¶à¸öÌõ¼þ¾ÙÐÐÅÌÎÊ¡£ÕâЩÌõ¼þ¿ÉÄÜ°üÀ¨×Ö¶ÎÖµ¡¢Ê±¼ä¹æÄ£¡¢¹ØϵµÈµÈ¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÌÖÂÛÔõÑùʹÓÃlaravel eloquent¾ÙÐжàÌõ¼þÅÌÎÊ¡£
»ù±¾ÅÌÎÊ
ÔÚLaravelÖоÙÐÐÅÌÎÊʱ£¬ÎÒÃÇ¿ÉÒÔʹÓûù±¾µÄÅÌÎÊÒªÁ죬ÀýÈçwhere¡¢orWhere¡¢whereIn¡¢whereNotInµÈ¡£ÕâЩÅÌÎÊÒªÁì¿ÉÒÔͨ¹ýÁ´Ê½Å²ÓÃÀ´×éºÏ¶à¸öÅÌÎÊÌõ¼þ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎÊÎÄÕ±íÖÐIDΪ1ÇÒ״̬Ϊ1µÄÎÄÕ£º
$article = DB::table('articles') ->where('id', 1) ->where('status', 1) ->first();
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃÇʹÓÃwhereÒªÁìÀ´Ö¸¶¨Á½¸öÌõ¼þ¡£firstÒªÁìÓÃÓÚ»ñÈ¡µ¥Ìõ¼Í¼£¬ÈôÊÇÅÌÎÊЧ¹ûΪ¿Õ£¬Ôò·µ»Ønull¡£
¸ß¼¶ÅÌÎÊ
LaravelÖеÄEloquentÄ£×Ó»¹ÌṩÁËÐí¶à¸ß¼¶ÅÌÎÊÒªÁìÀ´´¦Öóͷ£¸üÖØ´óµÄÅÌÎÊ¡£ÒÔÏÂÊÇһЩ³£Óõĸ߼¶ÅÌÎÊÒªÁ죺
2.1 whereBetweenÒªÁì
whereBetweenÒªÁìÔÊÐíÎÒÃÇÅÌÎÊÔÚÖ¸¶¨¹æÄ£Äڵļͼ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎʽ¨Éèʱ¼äÔÚ2019Äêµ½2020ÄêÖ®¼äµÄÎÄÕ£º
$articles = DB::table('articles') ->whereBetween('created_at', ['2019-01-01', '2020-12-31']) ->get();
µÇ¼ºó¸´ÖÆ
2.2 orWhereÒªÁì
orWhereÒªÁìÔÊÐíÎÒÃÇÅÌÎʶà¸öÌõ¼þÖеÄí§ÒâÒ»¸öÌõ¼þÖª×ã¼´¿É¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎÊ״̬Ϊ1»ò2µÄÎÄÕ£º
$articles = DB::table('articles') ->where('category_id', 1) ->orWhere('status', 1) ->get();
µÇ¼ºó¸´ÖÆ
2.3 whereHasÒªÁì
whereHasÒªÁìÔÊÐíÎÒÃÇÅÌÎʹØÁªÄ£×ÓÖÐÖª×ãɸѡÌõ¼þµÄ¼Í¼¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎÊËùÓÐÓÐ̸ÂÛµÄÎÄÕ£º
$articles = DB::table('articles') ->whereHas('comments') ->get();
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃÇʹÓÃÁËwhereHasÒªÁìÀ´ÅÌÎʹØÁªÄ£×ÓcommentsÖÐÊÇ·ñÓмͼ£¬²¢·µ»ØÖª×ãÌõ¼þµÄÎÄռͼ¡£ÈôÊÇÎÒÃÇÏ£Íû½øÒ»²½É¸Ñ¡Öª×ãÒ»¶¨Ìõ¼þµÄ̸ÂÛ£¬ÎÒÃÇ¿ÉÒÔÔÚwhereHasÒªÁìÖд«ÈëÌØÁíÍâɸѡÌõ¼þ£¬ÀýÈ磺
$articles = DB::table('articles') ->whereHas('comments', function($query) { $query->where('status', 1); }) ->get();
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃǶÔcommentsÄ£×Ó´«ÈëÅÌÎÊÌõ¼þ£¬½öÅÌÎÊ״̬Ϊ1µÄ̸ÂÛ£¬Í¬Ê±·µ»ØÓëÆä¹ØÁªµÄÎÄռͼ¡£
2.4 whereInºÍwhereNotInÒªÁì
whereInºÍwhereNotInÔÊÐíÎÒÃÇƾָ֤¶¨×ֶεÄÈ¡Öµ¹æģɸѡЧ¹û¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎÊÎÄÕÂ״̬Ϊ1¡¢2¡¢3µÄ¼Í¼£º
$articles = DB::table('articles') ->whereIn('status', [1, 2, 3]) ->get();
µÇ¼ºó¸´ÖÆ
»ìÏýʹÓÃ
ÏÖʵӦÓÃÖУ¬ÎÒÃÇÍùÍùÐèÒª×ÛºÏʹÓÃÒÔÉÏÅÌÎÊÒªÁìÀ´Íê³É¶àÌõ¼þÅÌÎÊ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÅÌÎÊ·ÖÀàIDΪ1ÇÒ״̬Ϊ1µÄÎÄÕ£¬²¢ÇÒ̸ÂÛÊý´óÓÚ5Ìõ£º
$articles = DB::table('articles') ->where('category_id', 1) ->where('status', 1) ->whereHas('comments', function($query) { $query->where('status', 1); }, '>', 5) ->get();
µÇ¼ºó¸´ÖÆ
ÔÚ±¾ÀýÖУ¬ÎÒÃÇʹÓÃÁËwhereHasÒªÁìÀ´ÅÌÎÊÖª×ãÒ»¶¨Ìõ¼þµÄ̸ÂÛ£¬²¢Ê¹ÓÃ>·ûºÅÀ´ÅÌÎÊ̸ÂÛÊýÊÇ·ñ´óÓÚ5Ìõ¡£
½áÂÛ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓöàÖÖ·½·¨À´¾ÙÐжàÌõ¼þÅÌÎÊ¡£Ê¹ÓÃEloquentÄ£×ӵĸ߼¶ÅÌÎÊÒªÁì¿ÉÒÔ¸üÀû±ãµØÍê³ÉÖØ´óµÄÅÌÎʲÙ×÷¡£ÕÆÎÕ¶àÌõ¼þÅÌÎʵļ¼ÇÉ¿ÉÒÔÈÃÎÒÃÇÔÚ¿ª·¢Öиü¸ßЧµØÍê³ÉʹÃü¡£
ÒÔÉϾÍÊÇlaravelÅÌÎÊд¶à¸öÌõ¼þµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡