laravelʵÏÖ¶àÌõ¼þÅÌÎÊ
×÷Ϊһ¿îÊ¢ÐÐµÄ php ¿ª·¢¿ò¼Ü£¬laravel ÒѾӮµÃÁËÖڶ࿪·¢Ö°Ô±µÄÇàíù¡£ÔÚÏÖʵ¿ª·¢ÖУ¬Ðí¶à³¡¾°ÐèÒª¶ÔÊý¾Ý¿â¾ÙÐжàÌõ¼þÅÌÎÊ£¬Õâʱ¼ä laravel ÌṩÁ˲»ÉÙÀû±ãµÄÒªÁìÀ´¾ÙÐд¦Öóͷ£¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓà laravel ʵÏÖ¶àÌõ¼þÅÌÎÊ¡£
»ù´¡ÖªÊ¶
ÔÚÏÈÈÝÏêϸʵÏÖÒªÁì֮ǰ£¬ÎÒÃÇÐèÒªÏàʶһЩ»ù´¡¿´·¨¡£
ÅÌÎʹ¹½¨Æ÷£ºLaravel µÄÅÌÎʹ¹½¨Æ÷ÌṩÁËÀû±ãµÄ¡¢Á÷ͨµÄ½Ó¿ÚÀ´²Ù×÷Êý¾Ý¿â¡£ÅÌÎʹ¹½¨Æ÷Ö§³Ö¼òÆ Where Ìõ¼þ¡¢ÅÅÐò¡¢·Ö×é¡¢¾ÛºÏµÈ²Ù×÷¡£
Eloquent ORM£ºÔÚ Laravel ÖУ¬Eloquent ORM ÊǶÔÊý¾Ý¿âµÄÒ»¸ö¹¤¾ß¹ØϵӳÉ䣨ORM£©ÊµÏÖ¡£ËüÌṩÁ˼òÆÓµÄÒªÁìÀ´²Ù×÷Êý¾Ý¿â±í¡£
ÅÌÎʹ¹½¨Æ÷
Laravel µÄÅÌÎʹ¹½¨Æ÷ÌṩÁ˶àÖÖÅÌÎÊÒªÁ죬°üÀ¨ where¡¢orWhere¡¢whereIn¡¢whereNotIn¡¢whereBetween¡¢whereNotBetween µÈµÈ¡£ÆäÖУ¬where ºÍ orWhere ÊÇ×îΪ³£ÓõÄÒªÁì¡£
ʹÓà where ÒªÁì¿ÉÒÔƾָ֤¶¨Ìõ¼þ¾ÙÐÐÅÌÎÊ¡£Ê¾Àý´úÂëÈçÏ£º
$users = DB::table('users')->where('name', 'John')->get();
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂ뽫´Ó users ±íÖÐÅÌÎÊÃû×ÖΪ John µÄËùÓÐÓû§¡£
ʹÓà orWhere ÒªÁì¿ÉÒÔÌí¼ÓÒ»¸ö»ò¶à¸ö¡°»ò¡±Ìõ¼þ¡£Ê¾Àý´úÂëÈçÏ£º
$users = DB::table('users') ->where('name', 'John') ->orWhere('name', 'Jane') ->get();
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂ뽫´Ó users ±íÖÐÅÌÎÊÃû×ÖΪ John »òÕß Jane µÄËùÓÐÓû§¡£
³ýÁË where ºÍ orWhere ÒªÁìÍ⣬Laravel ÅÌÎʹ¹½¨Æ÷»¹ÌṩÁËÆäËû¶àÖÖÅÌÎÊÒªÁ죬ÕâÀï²»ÔÙÖðһ׸Êö¡£¸ü¶àÒªÁìÏê¼û Laravel ¹Ù·½Îĵµ¡£
Eloquent ORM
Eloquent ORM ÊÇ Laravel µÄÒ»¸ö¹¤¾ß¹ØϵӳÉ䣨ORM£©ÊµÏÖ£¬ËüÔÊÐíÎÒÃÇʹÓà PHP ¹¤¾ß¶ø²»ÊÇ SQL Óï¾äÀ´²Ù×÷Êý¾Ý¿â±í¡£
ʹÓà Eloquent ORM ¾ÙÐÐÅÌÎÊÐèÒªÏȽç˵һ¸öÄ£×Ó£¬Ê¾Àý´úÂëÈçÏ£º
namespace App; use IlluminateDatabaseEloquentModel; class User extends Model { protected $table = 'users'; }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬User Ä£×Ó¶ÔÓ¦µÄÊý¾Ý¿â±íΪ users¡£
½ç˵ÍêÄ£×ÓÖ®ºó£¬ÎÒÃǾͿÉÒÔʹÓà Eloquent ORM ¾ÙÐжàÌõ¼þÅÌÎÊÁË¡£Ê¾Àý´úÂëÈçÏ£º
$users = User::where('name', 'John') ->orWhere('name', 'Jane') ->get();
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂ뽫´Ó users ±íÖÐÅÌÎÊÃû×ÖΪ John »òÕß Jane µÄËùÓÐÓû§£¬ÓëʹÓÃÅÌÎʹ¹½¨Æ÷µÄ·½·¨Ïàͬ¡£
³ýÁË where ºÍ orWhere ÒªÁìÍ⣬Eloquent ORM »¹ÌṩÁËÆäËû¶àÖÖÅÌÎÊÒªÁ죬ÕâÀï²»ÔÙÖðһ׸Êö¡£¸ü¶àÒªÁìÏê¼û Laravel ¹Ù·½Îĵµ¡£
¶àÌõ¼þÅÌÎÊʵÀý
ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃǾ³£ÐèÒª¾ÙÐжàÌõ¼þÅÌÎÊ¡£ÏÂÃæÒÔÒ»¸ö¼òÆÓµÄÓû§ÅÌÎÊΪÀý£¬ÏÈÈÝÔõÑùʹÓà Eloquent ORM ʵÏÖ¶àÌõ¼þÅÌÎÊ¡£
¼ÙÉèÎÒÃÇÓÐÒ»¸ö users ±í£¬ÆäÖаüÀ¨ÒÔÏÂ×ֶΣº
id
name
age
gender
ÎÒÃÇÐèÒªÅÌÎÊËùÓÐÖª×ãÒÔÏÂÌõ¼þµÄÓû§£º
gender ΪÄÐÐÔ
ÄêËêÔÚ 20 µ½ 30 ËêÖ®¼ä
Ãû×ÖÒÔ “J” ¿ªÍ·
ÓÊÏäÒÔ “@example.com” ×îºó
ʹÓà Eloquent ORM ¿ÉÒÔÈçÏÂʵÏÖ£º
$users = User::where('gender', 'male') ->whereBetween('age', [20, 30]) ->where('name', 'like', 'J%') ->where('email', 'like', '%@example.com') ->get();
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÊ×ÏÈʹÓà where ÒªÁìɸѡ³ö gender Ϊ male µÄÓû§£¬È»ºóʹÓà whereBetween ÒªÁìɸѡ³ö age ÔÚ 20 µ½ 30 ËêÖ®¼äµÄÓû§£¬ÔÙʹÓà where ÒªÁìɸѡ×ÅÃû×ÖÒÔ “J” ¿ªÍ·µÄÓû§£¬×îºóʹÓà where ÒªÁìɸѡ³öÓÊÏäÒÔ “@example.com” ×îºóµÄÓû§£¬²¢½«ËùÓÐÖª×ãÌõ¼þµÄÓû§´ò°ü³ÉÒ»¸öÜöÝÍ·µ»Ø¡£
×ܽá
¶àÌõ¼þÅÌÎÊÊÇ¿ª·¢Öг£¼ûµÄÐèÇó£¬ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÅÌÎʹ¹½¨Æ÷»ò Eloquent ORM À´ÊµÏÖ¶àÌõ¼þÅÌÎÊ¡£ÅÌÎʹ¹½¨Æ÷ÌṩÁ˶àÖÖÅÌÎÊÒªÁ죬¿ÉÒÔƾ֤ÏêϸÐèÇóÑ¡ÔñʹÓã»Eloquent ORM Ôò¿ÉÒÔʹÓÃÀàËÆÓÚ¹¤¾ßÒªÁìµÄ·½·¨À´¾ÙÐжàÌõ¼þÅÌÎÊ¡£ËäÈ»£¬Ê¹ÓÃÄÄÖÖ·½·¨È¡¾öÓÚÏêϸÇéÐκÍСÎÒ˽¼Òϲ»¶¡£ÎÞÂÛʹÓÃÄÄÖÖ·½·¨£¬ÎÒÃǶ¼¿ÉÒÔÀû±ãµØʵÏÖ¶àÌõ¼þÅÌÎÊ¡£
ÒÔÉϾÍÊÇlaravelʵÏÖ¶àÌõ¼þÅÌÎʵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡