laravelÔõôÅжÏÅÌÎÊЧ¹û
ÔÚlaravelÓ¦ÓóÌÐòÖУ¬ÎÒÃÇͨ³£ÐèÒªÅÌÎÊÊý¾Ý¿âÒÔ»ñÈ¡ËùÐèÊý¾Ý¡£ÔÚÕâЩÅÌÎÊʱ´ú£¬ÎÒÃÇÓÐʱÐèÒªÔÚ´úÂëÖбàдÌõ¼þÓï¾äÒÔ¼ì²éÅÌÎÊЧ¹û²¢Æ¾Ö¤Ð§¹û½ÓÄÉÏìÓ¦µÄ²½·¥¡£Òò´Ë£¬±¾ÎĽ«ÏÈÈÝÔõÑùÔÚlaravelÖÐÅжÏÅÌÎÊЧ¹û²¢±àдÌõ¼þÓï¾ä¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÏàʶLaravelÅÌÎÊ·µ»ØµÄЧ¹ûÀàÐÍ¡£LaravelÖеÄÅÌÎʻ᷵»Ø²î±ðµÄЧ¹ûÀàÐÍ£¬È¡¾öÓÚÄúÔÚÖ´ÐÐÅÌÎÊʱʹÓÃÄĸöÒªÁì¡£ÒÔÏÂÊÇһЩ×î³£ÓõÄÅÌÎÊÒªÁì¼°Æä·µ»ØÖµÀàÐÍ£º
get() – ·µ»ØÒ»¸öÅÌÎÊЧ¹ûÜöÝÍ(Collection)
first() – ·µ»Øµ¥¸öÄ£×ÓʵÀý(Model)
find() – ƾ֤ ID ²éÕÒµ¥¸öÄ£×ÓʵÀý(Model)
pluck() – ·µ»ØÒ»¸öµ¥¶ÀµÄÁÐÊý×é(Array)
count() – ·µ»ØÕûÊýÖµ(Int)
exists() – ·µ»Ø²¼¶ûÖµ(Boolean)
½ÓÏÂÀ´£¬ÎÒÃǽ«Ñ§Ï°ÔõÑùÅжÏÕâЩЧ¹ûÀàÐͲ¢±àдÌõ¼þÓï¾ä¡£
Collection
CollectionÊÇLaravelÖÐ×î³£ÓõÄЧ¹ûÀàÐÍÖ®Ò»¡£µ±ÎÒÃÇʹÓÃget()ÒªÁì¾ÙÐÐÅÌÎÊʱ£¬½«·µ»ØÒ»¸öCollectionʵÀý¡£
ÒªÅжÏCollectionÊÇ·ñΪ¿Õ£¬ÇëʹÓÃisEmpty()ÒªÁì¡£ÀýÈ磺
$users = DB::table('users')->get(); if ($users->isEmpty()) { // CollectionΪ¿ÕµÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // Collection²»Îª¿ÕµÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
ÈôÊÇÄúÖ»ÐèÒªÔÚCollectionÖнöÓÐÒ»Ìõ¼Í¼ʱִÐдúÂ룬ÇëʹÓÃisNotEmpty()ÒªÁì¡£ÀýÈ磺
$users = DB::table('users')->get(); if ($users->isNotEmpty()) { // CollectionÖÐÓмͼµÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // CollectionΪ¿ÕµÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
ÈôÊÇÄúÐèÒªÔÚCollectionÖвéÕÒÌض¨µÄ¼Í¼£¬ÇëʹÓÃcontains()ÒªÁì¡£ÀýÈ磺
$users = DB::table('users')->get(); if ($users->contains('name', 'John')) { // CollectionÖаüÀ¨¼Í¼µÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // CollectionÖв»°üÀ¨¼Í¼µÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
Model
µ±ÎÒÃÇʹÓÃfirst()ÒªÁì¾ÙÐÐÅÌÎÊʱ£¬½«·µ»ØÒ»¸öModelʵÀý¡£ÔÚÕâÖÖÇéÐÎÏ£¬ÎÒÃÇ¿ÉÒÔʹÓÃifÓï¾äÅжÏЧ¹ûÊÇ·ñΪ¿Õ¡£ÀýÈ磺
$user = DB::table('users')->where('email', 'john@example.com')->first(); if ($user) { // ModelʵÀý±£´æµÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // ModelʵÀý²»±£´æµÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
ͬÑù£¬ÈôÊÇÄúʹÓÃfind()ÒªÁì²éÕҼͼ£¬Ôò¿ÉÒÔʹÓÃifÓï¾äÅжÏЧ¹ûÊÇ·ñΪ¿Õ¡£ÀýÈ磺
$user = DB::table('users')->find(1); if ($user) { // ModelʵÀý±£´æµÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // ModelʵÀý²»±£´æµÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
Array
µ±Ê¹ÓÃpluck()ÒªÁì»ñÈ¡ÅÌÎÊÖеĵ¥¸öÁÐʱ£¬½«·µ»ØÒ»¸öÊý×é¡£ÔÚÕâÖÖÇéÐÎÏ£¬ÎÒÃÇ¿ÉÒÔʹÓÃempty()º¯ÊýÀ´¼ì²éÊý×éÊÇ·ñΪ¿Õ¡£ÀýÈ磺
$emails = DB::table('users')->pluck('email'); if (empty($emails)) { // Êý×éΪ¿ÕµÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // Êý×鲻Ϊ¿ÕµÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
Int
µ±Ê¹ÓÃcount()ÒªÁì»ñÈ¡ÅÌÎÊЧ¹ûµÄÊýĿʱ£¬½«·µ»ØÒ»¸öÕûÊýÖµ¡£ÔÚÕâÖÖÇéÐÎÏ£¬ÎÒÃÇ¿ÉÒÔʹÓÃifÓï¾ä¼ì²éЧ¹ûÊÇ·ñΪ0¡£ÀýÈ磺
$count = DB::table('users')->count(); if ($count == 0) { // ¼Í¼ÊýΪ0µÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // ¼Í¼Êý²»Îª0µÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
Boolean
µ±ÎÒÃÇʹÓÃexists()ÒªÁì¼ì²éÊÇ·ñ±£´æ¼Í¼ʱ£¬½«·µ»ØÒ»¸ö²¼¶ûÖµ¡£ÀýÈ磺
if (DB::table('users')->where('name', 'John')->exists()) { // ±£´æ¼Í¼µÄÇéÐÎÏÂÖ´ÐеĴúÂë } else { // ²»±£´æ¼Í¼µÄÇéÐÎÏÂÖ´ÐеĴúÂë }
µÇ¼ºó¸´ÖÆ
×ܽá
ÔÚLaravelÓ¦ÓóÌÐòÖУ¬ÎÒÃÇͨ³£ÐèҪƾ֤²î±ðµÄÅÌÎÊЧ¹û±àдÌõ¼þÓï¾ä¡£±¾ÎÄÏÈÈÝÁËÔõÑùÅжÏCollection¡¢Model¡¢Array¡¢IntºÍBooleanÀàÐ͵ÄÅÌÎÊЧ¹û£¬²¢ÌṩÁËÏìÓ¦µÄʾÀý´úÂ롣ͨ¹ýÕâЩʾÀý£¬ÎÒÃÇ¿ÉÒÔÔ½·¢ÎÞаµØʹÓÃLaravelÅÌÎÊÒªÁì²¢´¦ÀíÖÖÖÖÇéÐΡ£
ÒÔÉϾÍÊÇlaravelÔõôÅжÏÅÌÎÊЧ¹ûµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡