laravel ÓÅ»¯ÅÌÎÊЧÂÊ
ÔÚ¿ª·¢ web Ó¦ÓóÌÐòʱ£¬ÅÌÎÊÊý¾Ý¿âÊDz»¿É×èÖ¹µÄÊÂÇ飬ÓÈÆäÊǵ±Êý¾ÝÁ¿´óµÄʱ¼ä£¬ÅÌÎʵÄЧÂÊ»áÑÏÖØÓ°ÏìÓ¦ÓóÌÐòµÄÐÔÄܺÍÓû§ÌåÑé¡£¶Ô´Ë£¬ÎÒÃÇ¿ÉÒÔͨ¹ýһЩÓÅ»¯·½·¨À´Ìá¸ßÅÌÎÊЧÂÊ£¬ÌØÊâÊÇÔÚʹÓà laravel ¿ò¼ÜµÄÇéÐÎÏ¡£
ÏÂÃ潫ÏÈÈÝһЩÓÅ»¯ Laravel ÅÌÎÊЧÂʵÄÒªÁ죺
ʹÓÃË÷Òý
Ë÷ÒýÊÇÒ»ÖÖÊý¾Ý¿â¹¤¾ß£¬ÓÃÓÚ¶Ô±íÖеÄÁÐÖµ¾ÙÐÐÅÅÐòºÍ²éÕÒ¡£½¨ÉèË÷Òý¿ÉÒÔ¼ÓËÙÅÌÎʺÍÊý¾Ý»á¼ûËÙÂÊ¡£ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃǨáãÎļþÀ´Îª±íµÄÁн¨ÉèË÷Òý¡£ÀýÈ磺
// Ϊ users ±íµÄ email Áн¨ÉèË÷Òý Schema::table('users', function (Blueprint $table) { $table->index('email'); });
µÇ¼ºó¸´ÖÆ
±ðµÄ£¬»¹¿ÉÒÔʹÓà unique() ÒªÁìÀ´ÎªÁн¨ÉèΨһË÷Òý¡£ÀýÈ磺
// Ϊ users ±íµÄ email Áн¨ÉèΨһË÷Òý Schema::table('users', function (Blueprint $table) { $table->unique('email'); });
µÇ¼ºó¸´ÖÆ
ÐèҪעÖصÄÊÇ£¬½¨Éè¹ý¶àµÄË÷ÒýÒ²»á½µµÍÊý¾Ý¿âµÄÐÔÄÜ£¬Òò´ËÎÒÃÇÐèҪƾ֤ÐèҪѡÔñºÏÊʵÄË÷Òý¡£
ʹÓÃÈíɾ³ý
Laravel ÖеÄÈíɾ³ýÊÇÖ¸½«±»É¾³ýµÄÊý¾Ý±ê¼ÇΪÒÑɾ³ý£¬¶ø²»ÊÇÖ±½Ó´ÓÊý¾Ý¿âÖÐɾ³ý¡£ÕâÑù×öµÄÀûÒæÊÇ¿ÉÒÔ±ÜÃâÎóɾ³ýÊý¾Ý£¬²¢ÇÒ¿ÉÒÔÔÚÐèҪʱÇáËɵػָ´ÒÑɾ³ýµÄÊý¾Ý¡£ÔÚÅÌÎÊʱ£¬Laravel ĬÈϲ»°üÀ¨ÒÑɾ³ýµÄÊý¾Ý¡£Òò´Ë£¬ÈôÊÇÎÒÃÇÔÚɾ³ýÊý¾ÝʱʹÓÃÈíɾ³ý£¬¿ÉÒÔïÔÌÅÌÎÊÊý¾ÝµÄÊýÄ¿£¬´Ó¶øÌá¸ßÅÌÎÊЧÂÊ¡£
ҪʹÓÃÈíɾ³ý£¬Ö»ÐèΪģ×ÓÌí¼Ó SoftDeletes trait£¬²¢ÔÚÏìÓ¦µÄÊý¾Ý±íÖÐÌí¼Ó deleted_at Áм´¿É¡£ÀýÈ磺
use IlluminateDatabaseEloquentModel; use IlluminateDatabaseEloquentSoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
µÇ¼ºó¸´ÖÆ
ʹÓûº´æ
»º´æÊÇÒ»ÖÖ³£ÓõÄÓÅ»¯ÅÌÎÊЧÂʵÄÒªÁ졣ͨ¹ý½«¾³£±»»á¼ûµÄÊý¾Ý»º´æµ½ÄÚ´æÖУ¬ïÔÌÁËÖظ´ÅÌÎʵĴÎÊý£¬¼ÓËÙÁËÊý¾Ý»á¼ûËÙÂÊ¡£ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓûº´æÀ´´æ´¢ÅÌÎÊЧ¹û¡£ÀýÈ磺
// ½«ÅÌÎÊЧ¹û»º´æ 10 ·ÖÖÓ $users = Cache::remember('users', 10, function () { return DB::table('users')->get(); });
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓÃÁË Cache::remember() ÒªÁìÀ´»º´æÅÌÎÊЧ¹û¡£¸ÃÒªÁìµÄµÚÒ»¸ö²ÎÊýÊÇ»º´æµÄ¼üÃû£¬µÚ¶þ¸ö²ÎÊýÊÇ»º´æµÄʱ¼ä£¬µÚÈý¸ö²ÎÊýÊÇÖ´ÐÐÅÌÎʵıհüº¯Êý¡£
ÀÁ¶è¼ÓÔØ
ÔÚÅÌÎʹØÁªÄ£×Óʱ£¬Laravel ĬÈÏʹÓÃÀÁ¶è¼ÓÔØ¡£¼´Ö»ÓÐÔÚ»á¼û¹ØÁªÄ£×Óʱ²Å»áÖ´ÐÐÅÌÎÊ¡£ÕâÖÖ·½·¨¿ÉÒÔ×èÖ¹ÔÚÅÌÎÊʱͬʱÅÌÎÊ´ó×ڵĹØÁªÊý¾Ý£¬´Ó¶øÌá¸ßÁËÅÌÎÊЧÂÊ¡£ÀýÈ磺
$post = Post::find(1); // µ±ÐèÒª»á¼û comments ʱ£¬²Å»áÖ´ÐÐÅÌÎÊ foreach ($post->comments as $comment) { // }
µÇ¼ºó¸´ÖÆ
ÐèҪעÖصÄÊÇ£¬ÈôÊÇÅÌÎÊʱÐèҪͬʱ»á¼û´ó×ڵĹØÁªÊý¾Ý£¬ÕÕ¾ÉÒªÎÈÖØ˼Á¿Ê¹ÓÃÀÁ¶è¼ÓÔØ¡£
Ô¤¼ÓÔØ
Ô¤¼ÓÔØÊÇÖ¸ÔÚÅÌÎÊʱһ´ÎÐÔÅÌÎÊËùÐèÊý¾ÝºÍ¹ØÁªÊý¾Ý£¬²¢½«Æä´æ´¢ÔÚÄÚ´æÖС£ÕâÑù¿ÉÒÔïÔÌÅÌÎʵĴÎÊý£¬Ìá¸ßÅÌÎÊЧÂÊ¡£ÔÚ Laravel ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓà with() ÒªÁìÀ´¾ÙÐÐÔ¤¼ÓÔØ¡£ÀýÈ磺
$posts = Post::with('comments')->get();
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓà with() ÒªÁìÀ´Ô¤¼ÓÔØÁË comments ¹ØÁªÄ£×Ó¡£ÕâÑù¿ÉÒÔÔÚÅÌÎÊʱһ´ÎÐÔÅÌÎÊËùÓеÄÌû×ÓºÍ̸ÂÛ£¬²¢Ò»Í¬·µ»Ø¸ø¿Í»§¶Ë¡£
×ܽáһϣ¬Í¨¹ýʹÓÃË÷Òý¡¢Èíɾ³ý¡¢»º´æ¡¢ÀÁ¶è¼ÓÔغÍÔ¤¼ÓÔصȼ¼ÇÉ£¬¿ÉÒÔÓÐÓÃÓÅ»¯ Laravel ÅÌÎÊЧÂÊ£¬Ìá¸ßÓ¦ÓóÌÐòµÄÐÔÄܺÍÓû§ÌåÑé¡£
ÒÔÉϾÍÊÇlaravel ÓÅ»¯ÅÌÎÊЧÂʵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡