laravelÔõô·µ»ØÖ¸¶¨ÁÐ
laravelÊÇÒ»¿îÊ¢ÐеÄphp¿ò¼Ü£¬ËüÄܹ»×ÊÖúweb¿ª·¢ÕßÇáËɹ¹½¨¸ßЧµÄwebÓ¦ÓóÌÐò¡£ÔÚlaravelÖУ¬·µ»ØÖ¸¶¨ÁÐÊǷǾ³£¼ûµÄÐèÇó¡£±¾ÎĽ«ÏÈÈÝlaravelÔõÑù·µ»ØÖ¸¶¨ÁС£
ÔÚLaravelÖУ¬ÈôÊÇÏëÒª·µ»ØÖ¸¶¨ÁУ¬¿ÉÒÔʹÓÃEloquentÄ£×Ó¡£EloquentÊÇLaravelµÄORM£¨¹¤¾ß¹ØϵӳÉ䣩¿ò¼Ü£¬ËüΪÎÒÃÇÌṩÁËÒ»ÖÖ¼òÆÓ¡¢ÓÅÑŵķ½·¨À´ÖÎÀíÊý¾Ý¿â¡£ÒÔÏÂÊÇʹÓÃEloquentÄ£×ÓÔõÑù·µ»ØÖ¸¶¨Áеİ취£º
°ì·¨Ò»£º½ç˵EloquentÄ£×Ó
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½ç˵һ¸öEloquentÄ£×Ó¡£ÔÚLaravelÓ¦ÓóÌÐòÖУ¬ËùÓеÄEloquentÄ£×Ó¶¼Î»ÓÚappĿ¼ÏµÄModelsÎļþ¼ÐÖС£ÎÒÃÇ¿ÉÒÔͨ¹ýʹÓÃartisanÏÂÁîÐй¤¾ßÀ´½¨ÉèÒ»¸öеÄÄ£×Ó£¬ÈçÏÂËùʾ£º
php artisan make:model User
µÇ¼ºó¸´ÖÆ
Õ⽫ÔÚModelsÎļþ¼ÐÖн¨ÉèÒ»¸öÃûΪUserµÄEloquentÄ£×Ó¡£ÎÒÃÇ¿ÉÒÔÔÚ´ËÄ£×ÓÖнç˵ÎÒÃǵÄÊý¾Ý¿â±íºÍ×ֶΡ£
°ì·¨¶þ£º½ç˵Êý¾Ý¿â×Ö¶Î
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚEloquentÄ£×ÓÖнç˵ÎÒÃǵÄÊý¾Ý¿â±íºÍ×ֶΡ£ÎÒÃÇ¿ÉÒÔÔÚUserÄ£×ÓÖнç˵ÎÒÃǵÄÊý¾Ý¿â±íºÍ×ֶΣ¬ÈçÏÂËùʾ£º
namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class User extends Model { use HasFactory; protected $table = 'users'; protected $fillable = [ 'name', 'email', 'password', ]; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇͨ¹ýʹÓÃ$tableÊôÐÔÀ´½ç˵Êý¾Ý¿â±íµÄÃû³Æ£¬$fillableÊôÐÔÀ´½ç˵¿ÉÒÔÌî³äµ½Êý¾Ý¿âµÄ×ֶΡ£
°ì·¨Èý£º·µ»ØÖ¸¶¨ÁÐ
ÏÖÔÚ£¬ÎÒÃÇÒѾ½ç˵ÁËEloquentÄ£×ÓºÍÊý¾Ý¿â×ֶΣ¬ÎÒÃÇÖ»ÐèÒªÔÚÎÒÃǵĿØÖÆÆ÷ÖÐŲÓÃÊý¾Ý¿âÅÌÎÊ£¬²¢·µ»ØÖ¸¶¨Áм´¿É¡£ÀýÈ磬ÈôÊÇÎÒÃÇÖ»Ïë»ñÈ¡Óû§µÄEmailµØµã£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÔÚÎÒÃǵĿØÖÆÆ÷ÖÐŲÓÃÈçÏ´úÂëÀ´ÊµÏÖ£º
namespace AppHttpControllers; use AppModelsUser; class UserController extends Controller { public function index() { $users = User::select('email')->get(); return $users; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃÁËselectÒªÁìÀ´Ñ¡ÔñÎÒÃÇÒª·µ»ØµÄ×ֶΡ£ÔÚÎÒÃǵÄÀý×ÓÖУ¬ÎÒÃÇֻѡÔñÁËemail×ֶΡ£ÎÒÃÇ»¹Ê¹ÓÃÁËgetÒªÁìÀ´»ñÈ¡ËùÓÐÓû§µÄEmailµØµã¡£×îºó£¬ÎÒÃǽ«Ð§¹û·µ»Ø¸øÎÒÃǵÄÊÓͼ»òÕßÒÔJSONÃûÌ÷µ»Ø¸øAPI¡£
³ýÁËʹÓÃselectÒªÁ죬ÎÒÃÇ»¹¿ÉÒÔʹÓÃpluckÒªÁìÀ´Ö»·µ»ØÒ»¸öÌض¨µÄ×ֶΣ¬ÈçÏÂËùʾ£º
$email = User::pluck('email');
µÇ¼ºó¸´ÖÆ
×ܽá
ÔÚLaravelÖУ¬Ê¹ÓÃEloquentÄ£×Ó¿ÉÒÔÀû±ãµØ·µ»ØÖ¸¶¨µÄÁС£ÎÒÃÇ¿ÉÒÔʹÓÃselectÒªÁìÀ´Ñ¡ÔñÎÒÃÇÒª·µ»ØµÄ×ֶΣ¬»òÕßʹÓÃpluckÒªÁìÀ´·µ»ØÒ»¸öÌض¨µÄ×ֶΡ£ÕâʹµÃLaravelÔÚ´¦Àí´óÐÍÊý¾Ý±íʱԽ·¢¸ßЧ£¬²¢¼ò»¯ÁËÎÒÃǵĴúÂë¡£
ÒÔÉϾÍÊÇlaravelÔõô·µ»ØÖ¸¶¨ÁеÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡