laravel ÅÌÎÊÓï·¨
laravelÊÇÏÖÏÖÔÚºÜÊÇÊ¢ÐеÄphp¿ò¼ÜÖ®Ò»£¬ËüµÄÅÌÎÊÓï·¨ÓÅÑżòÆÓ£¬Ò×ÓÚʹÓá£ÔÚÕâƪÎÄÕÂÖУ¬ÎÒ½«ÉîÈë̽ÌÖlaravelµÄÅÌÎÊÓï·¨£¬ÏÈÈÝһЩ³£ÓõÄÅÌÎÊÒªÁ죬ÒÔ¼°ÔõÑù¾ÙÐÐÖØ´óµÄÅÌÎÊ¡£
LaravelÅÌÎʵĻù´¡Óï·¨
ÔÚLaravelÖУ¬ÅÌÎÊÓï¾äÊÇʹÓÃEloquent ORMÀ´¹¹½¨µÄ¡£ORM¼´¹¤¾ß¹ØϵӳÉ䣬ËüÔÊÐíÎÒÃÇÒÔÃæÏò¹¤¾ßµÄ·½·¨À´²Ù×÷Êý¾Ý¿â£¬¼«´óµØ¼ò»¯ÁËÓëÊý¾Ý¿âµÄ½»»¥Àú³Ì¡£
ÒÔÏÂÊÇʹÓÃLaravelÅÌÎÊÓï·¨µÄʾÀý£º
//»ñÈ¡µ¥¸öÓû§
$user = User::find(1);
//»ñÈ¡Óû§Áбí
$users = User::all();
//Ìõ¼þɸѡ£¬»ñÈ¡Ö¸¶¨Ìõ¼þϵÄÓû§Áбí
$users = User::where(‘age’, ‘>’, 18)->get();
//¸üÐÂÊý¾Ý
$user->name = ‘new name’;
$user->save();
//ɾ³ýÊý¾Ý
$user->delete();
ÈçÉÏËùʾ£¬Ê¹ÓÃLaravelÅÌÎÊÓï·¨£¬¿ÉÒÔÀû±ãµØʵÏÖ»ù±¾µÄCURD²Ù×÷¡£ÏÂÃæÎÒÃǽ«ÏÈÈÝһЩ³£ÓõÄÅÌÎÊÒªÁì¡£
³£ÓõÄÅÌÎÊÒªÁì
where()
where()ÒªÁìÊǷǾ³£¼ûµÄÌõ¼þɸѡҪÁ졣ƾ֤¸ø¶¨µÄÌõ¼þɸѡ³öÇкÏÒªÇóµÄ¼Í¼¡£ÀýÈ磺
$users = User::where(‘age’, ‘>’, 18)->where(‘gender’, ‘male’)->get();
where()ÒªÁ컹¿ÉÒÔÎüÊÕµÚÈý¸ö²ÎÊý£¬ÓÃÓÚÖ¸¶¨²Ù×÷·û£¬ÀýÈ磺
$users = User::where(‘age’, ‘>=’, 18)->get();
orderBy()
orderBy()ÒªÁìÓÃÓÚÅÅÐò¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔƾ֤Óû§µÄÄêËê¾ÙÐÐÅÅÐò£º
$users = User::orderBy(‘age’)->get();
ĬÈÏÇéÐÎÏ£¬orderBy()ÒªÁìÊÇƾ֤ÉýÐòÅÅÁеġ£ÈôÊÇҪƾ֤½µÐòÅÅÁУ¬Ôò¿ÉÒÔת´ïÒ»¸öDESC²ÎÊý£º
$users = User::orderBy(‘age’, ‘desc’)->get();
ÁíÍ⣬orderBy()ÒªÁì¿ÉÒÔÎüÊÕ¶à¸ö²ÎÊý£¬ÓÃÓÚÖ¸¶¨¶à¸öÅÅÐòÌõ¼þ£º
$users = User::orderBy(‘age’, ‘desc’)->orderBy(‘name’)->get();
select()
select()ÒªÁìÓÃÓÚÅÌÎÊÖ¸¶¨µÄÁС£ÀýÈ磺
$users = User::select(‘name’, ’email’)->get();
Ò²¿ÉÒÔʹÓÃ*À´ÅÌÎÊËùÓÐÁУº
$users = User::select(‘*’)->get();
take()ºÍskip()
take()ÒªÁìÓÃÓÚÏÞÖÆ·µ»ØµÄ¼Í¼Êý£¬skip()ÔòÊÇÓÃÓÚÌø¹ýÖ¸¶¨ÃüÄ¿µÄ¼Í¼¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÅÌÎÊÇ°10ÃûÓû§£º
$users = User::take(10)->get();
Ò²¿ÉÒÔÓÃskip()ÒªÁìÀ´ÊµÏÖ·ÖÒ³£º
$users = User::skip(10)->take(10)->get();
whereIn()ºÍwhereNotIn()
whereIn()¡¢whereNotIn()ÒªÁì¿ÉÒÔÓÃÓÚÔÚÅÌÎÊÖÐʹÓÃINºÍNOT IN¡£ÀýÈ磬»ñÈ¡ÄêËêÔÚ18ËêÒÔϵÄÓû§¿ÉÒÔÕâÑùд£º
$users = User::whereIn(‘age’, [16, 17, 18])->get();
whereNull()ºÍwhereNotNull()
whereNull()ÒªÁì¿ÉÒÔɸѡ³öÖ¸¶¨ÁÐΪ¿ÕµÄ¼Í¼£¬whereNotNull()Ôò¿ÉÒÔɸѡ³ö²»Îª¿ÕµÄ¼Í¼¡£ÀýÈ磺
$users = User::whereNull(’email’)->get();
groupBy()ºÍhaving()
groupBy()ÒªÁìÓÃÓÚ¶ÔЧ¹û¼¯¾ÙÐзÖ×飬¶øhaving()ÒªÁìÓÃÓÚɸѡ·Ö×éºóµÄЧ¹û¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔƾ֤ÐÔ±ð·Ö×飬²¢É¸Ñ¡³öÄÐÐÔÓû§ÖÐÄêËêÔÚ20ËêÒÔÉϵÄÓû§£º
$users = User::groupBy(‘gender’)->having(‘age’, ‘>’, 20)->get();
ÖØ´óÅÌÎÊ
ÉÏÃæÏÈÈݵÄÊÇLaravelÅÌÎÊÓï·¨µÄһЩ»ù±¾Ó÷¨¡£¿ÉÊÇ£¬ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃÇͨ³£ÐèÒªÅÌÎʵÄÊý¾Ý¿ÉÄܺÜÊÇÖØ´ó£¬ÐèҪʹÓøü¶àµÄÅÌÎÊÒªÁìÀ´ÊµÏÖ¡£ÔÚLaravelÖУ¬¿ÉÒÔʹÓÃQuery BuilderÀ´±àд¸üÖØ´óµÄÅÌÎÊÓï¾ä¡£
ÀýÈ磬ΪÁËÅÌÎÊÓû§µÄ¹ºÖüͼÖÐÀÛ»ýÏûºÄÁè¼Ý500ÔªµÄÓû§£¬¿ÉÒÔÕâÑùд£º
$users = DB::table(‘users’)
->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.id', 'users.name', 'users.email', DB::raw('SUM(orders.total) as total')) ->groupBy('users.id') ->having('total', '>', 500) ->get();
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃÁËjoin()ÒªÁìÀ´ÅþÁ¬Óû§±íºÍ¶©µ¥±í£¬Ê¹ÓÃÁËgroupBy()ÒªÁìÀ´¶ÔÓû§¾ÙÐзÖ×飬ʹÓÃÁËhaving()ÒªÁìÀ´É¸Ñ¡³öÀÛ»ýÏûºÄÁè¼Ý500ÔªµÄÓû§¡£
×ܽá
ÔÚLaravelÖУ¬Ê¹ÓÃEloquent ORM¿ÉÒÔÇáËÉʵÏÖ»ù±¾µÄCURD²Ù×÷¡£Í¬Ê±£¬Ê¹ÓÃQuery Builder¿ÉÒÔʵÏÖ¸üÖØ´óµÄÅÌÎÊ¡£Ï£Íû±¾ÎĶÔÄúÏàʶLaravelµÄÅÌÎÊÓï·¨ÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇlaravel ÅÌÎÊÓï·¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡