laravel dbÅÌÎÊÓï¾ä
laravelÊÇÒ»¿î¹¦Ð§Ç¿Ê¢µÄphp¿ò¼Ü£¬ÔÚ¿ª·¢webÓ¦ÓÃʱ£¬laravelÌṩÁËÐí¶à±ã½ÝµÄ¹¦Ð§£¬ÆäÖÐÊý¾Ý¿âÅÌÎʹ¦Ð§ÊÇ¿ª·¢Õß±ØÐèÕÆÎյġ£
±¾ÎĽ«ÏÈÈÝLaravelÖг£ÓõÄÊý¾Ý¿âÅÌÎÊÓï¾ä£¬°üÀ¨»ù±¾ÅÌÎÊ¡¢¾ÛºÏÅÌÎÊ¡¢Ìõ¼þÅÌÎʺ͹ØÁªÅÌÎʵȣ¬ÒÔ×ÊÖú¿ª·¢Õ߸üºÃµØʹÓÃLaravel¿ò¼Ü¾ÙÐÐÊý¾Ý¿â²Ù×÷¡£
»ù±¾ÅÌÎÊ
LaravelÖÐ×î»ù±¾µÄÅÌÎÊÓï¾äÊÇselectÓï¾ä£¬ÓÃÓÚÅÌÎÊÊý¾Ý±íÖеÄÊý¾Ý¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄÅÌÎÊʾÀý£º
$users = DB::table('users')->get();
µÇ¼ºó¸´ÖÆ
´Ë´úÂë´Óusers±íÖлñÈ¡ËùÓÐÊý¾Ý£¬²¢½«Ð§¹û´æ´¢ÔÚ$users±äÁ¿ÖС£
³ý´ËÖ®Í⣬Laravel»¹ÌṩÁËһЩ¼òÆÓµÄÅÌÎʸ¨Öúº¯Êý£¬ÀýÈ磬»ñÈ¡±íÖеĵÚÒ»Ìõ¼Í¼£º
$user = DB::table('users')->first();
µÇ¼ºó¸´ÖÆ
ÅÌÎÊÌض¨µÄÊý¾ÝÁУº
$users = DB::table('users')->select('name', 'email')->get();
µÇ¼ºó¸´ÖÆ
´Ó×Ó¾äÖйýÂËÊý¾Ý£º
$users = DB::table('users')->where('name', '=', 'John')->get();
µÇ¼ºó¸´ÖÆ
¾ÛºÏÅÌÎÊ
ÔÚLaravelÖУ¬¾ÛºÏº¯ÊýÓÃÓÚÅÌÎʺÍÅÌËãÊý¾Ý±íµÄ¾ÛºÏÖµ£¬ÈçÅÌËã×î´óÖµ¡¢×îСֵ¡¢Æ½¾ùÖµ¡¢×ܺ͵ȡ£ÏÂÃæÊÇһЩ³£¼ûµÄ¾ÛºÏº¯ÊýµÄ´úÂëʾÀý£º
ÅÌËã×ܼͼÊý£º
$count = DB::table('users')->count();
µÇ¼ºó¸´ÖÆ
ÅÌËã×î´óÖµ£º
$max = DB::table('users')->max('age');
µÇ¼ºó¸´ÖÆ
ÅÌËãƽ¾ùÖµ£º
$avg = DB::table('users')->avg('age');
µÇ¼ºó¸´ÖÆ
ÅÌËã×ܺͣº
$total = DB::table('users')->sum('age');
µÇ¼ºó¸´ÖÆ
Ìõ¼þÅÌÎÊ
LaravelÖеÄÌõ¼þÅÌÎÊ°üÀ¨Ê¹ÓÃwhereÓï¾ä¾ÙÐÐÌõ¼þÆ¥Å䣬ʹÓÃorWhereÓï¾äʵÏÖ¶àÌõ¼þÆ¥Å䣬ÒÔ¼°Ê¹ÓÃwhereInºÍorWhereInÓï¾äʵÏÖÅÌÎÊ°üÀ¨ÔÚÖ¸¶¨ÁбíÖеļͼ¡£ÏÂÃæÊÇһЩÌõ¼þÅÌÎʵĴúÂëʾÀý£º
ʹÓÃwhereÓï¾äʵÏÖÌõ¼þÆ¥Å䣺
$users = DB::table('users') ->where('name', '=', 'John') ->where('age', '>', 25) ->get();
µÇ¼ºó¸´ÖÆ
ʹÓÃorWhereÓï¾äʵÏÖ¶àÌõ¼þÆ¥Å䣺
$users = DB::table('users') ->where('name', '=', 'John') ->orWhere('age', '>', 25) ->get();
µÇ¼ºó¸´ÖÆ
ʹÓÃwhereInºÍorWhereInÓï¾äʵÏÖÅÌÎÊ°üÀ¨ÔÚÖ¸¶¨ÁбíÖеļͼ£º
$users = DB::table('users') ->whereIn('id', [1, 2, 3]) ->get(); $users = DB::table('users') ->orWhereIn('id', [1, 2, 3]) ->get();
µÇ¼ºó¸´ÖÆ
¹ØÁªÅÌÎÊ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ýjoinÓï¾äʵÏÖ±íÖ®¼äµÄ¹ØÁªÅÌÎÊ¡£¹ØÁªÅÌÎÊ¿ÉÒÔʹÓöàÖÖ²î±ðµÄ·½·¨£¬ÀýÈ磬ʹÓÃinnerJoin¡¢leftJoinºÍrightJoinµÈ¡£ÏÂÃæÊÇһЩ¹ØÁªÅÌÎʵĴúÂëʾÀý£º
ʹÓÃinnerJoinÓï¾äʵÏÖÄÚÅþÁ¬£º
$users = DB::table('users') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.name', 'orders.price') ->get();
µÇ¼ºó¸´ÖÆ
ʹÓÃleftJoinÓï¾äʵÏÖ×óÅþÁ¬£º
$users = DB::table('users') ->leftJoin('orders', 'users.id', '=', 'orders.user_id') ->select('users.name', 'orders.price') ->get();
µÇ¼ºó¸´ÖÆ
ʹÓÃrightJoinÓï¾äʵÏÖÓÒÅþÁ¬£º
$users = DB::table('users') ->rightJoin('orders', 'users.id', '=', 'orders.user_id') ->select('users.name', 'orders.price') ->get();
µÇ¼ºó¸´ÖÆ
ÒÔÉÏÊÇLaravelÖг£ÓõÄÊý¾Ý¿âÅÌÎÊÓï¾äÏÈÈÝ£¬¿ª·¢Õß¿ÉÒÔƾ֤ÏÖʵÐèÇóÎÞаÔËÓ㬿ìËÙ¸ßЧµØ¾ÙÐÐÊý¾Ý¿âÅÌÎʲÙ×÷¡£³ý´ËÖ®Í⣬Laravel»¹ÌṩÁËÆäËûÇ¿Ê¢µÄÊý¾Ý¿â²Ù×÷¹¦Ð§£¬ÈçÊÂÎñ´¦Àí¡¢·ÖÒ³ºÍÊý¾Ý¿âǨáãµÈ£¬ÕâЩ¹¦Ð§¿ÉÒÔ¸üºÃµØ×ÊÖú¿ª·¢ÕßÖÎÀíºÍά»¤Êý¾Ý¿â£¬ÌáÉý¿ª·¢Ð§ÂÊ¡£
ÒÔÉϾÍÊÇlaravel dbÅÌÎÊÓï¾äµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡