Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel Èíɾ³ýºÍ»Ö¸´Æ¬¶Ï£¿
laravel¿ª·¢£ºÔõÑùʹÓÃlaravel Èíɾ³ýºÍ»Ö¸´Æ¬¶Ï£¿
ÔÚLaravel¿ò¼ÜÖУ¬Èíɾ³ý£¨Soft Delete£©ÊÇÒ»¸öºÜÊÇÊÊÓõĹ¦Ð§£¬Ëû¿ÉÒԺܺõØ×ÊÖúÎÒÃÇ´¦ÀíÊý¾ÝµÄɾ³ý²Ù×÷¡£ÔÚÏÖʵӦÓÃÖУ¬ÓÐЩÊý¾Ý²¢²»ÊÇÕæÕýÒâÒåϵÄɾ³ý£¬¶øÊÇÖ»×ö±ê¼Ç£¬ÇÒÔÚÒ»¶¨µÄʱÏÞÖ®ÄÚ¿ÉÒÔ¾ÙÐлָ´µÄ²Ù×÷¡£
LaravelÌṩÁ˺ÜÊÇÀû±ãµÄÈíɾ³ý»úÖÆ£¬¿ÉÒÔͨ¹ýÔÚÄ£×ÓÖÐÌí¼ÓÈíɾ³ýµÄÏà¹ØÉèÖ㬴Ӷø¼òÆÓµØʵÏÖÈíɾ³ý¹¦Ð§¡£ÏÂÃæÎÒÃǽ«ÏêϸÏÈÈÝÔõÑùʹÓÃLaravel Èíɾ³ýºÍ»Ö¸´Æ¬¶Ï¡£
Ò»¡¢ÉèÖÃÄ£×ÓÈíɾ³ý
1.ÔÚÄ£×ÓÖУ¬Ìí¼ÓÒÔÏ´úÂ룺
µã»÷ÏÂÔØ¡°àËÃûÌÃÊý¾Ý»Ö¸´¾Þ½³¡±£»
use IlluminateDatabaseEloquentSoftDeletes; class MyModel extends Model { use SoftDeletes; protected $dates = ['deleted_at']; // ... }
µÇ¼ºó¸´ÖÆ
2.ʹÓÃÁËLaravel µÄ SoftDeletes trait ÌØÕ÷£¬¸ÃÌØÕ÷»áÔÚÄ£×ÓÖÐ×Ô¶¯ÆôÓÃÈíɾ³ý¹¦Ð§¡£
3.$dates ÊôÐÔÊÇ Laravel ¿ò¼ÜĬÈϵÄÒ»ÖÖÈÕÆÚÃûÌÃת»»£¬Ò»Ñùƽ³£ÓÃÔÚÊý¾Ý¿âÖÐ datetime¡¢date »ò timestamp ×Ö¶ÎÉÏ£¬Ëü¿É½ÓÊܸÃ×ֶεÄÊý×飬ÓÃÀ´½«¸Ã×Ö¶Î×Ô¶¯×ª³É Carbon ʵÀý²¢ÃûÌû¯¡£
4.ÔÚÄ£×ÓÖУ¬»á×Ô¶¯ÔÚ¶ÔÓ¦µÄÊý¾Ý±íÖÐÌí¼ÓÒ»¸ö deleted_at ×ֶΣ¬²¢ÇÒÔÚÖ´ÐÐɾ³ý²Ù×÷ʱ£¬»á°Ñ¸Ã×Ö¶ÎÉèÖÃΪĿ½ñʱ¼ä£¬´Ó¶øʵÏÖÈíɾ³ýµÄ¹¦Ð§¡£
¶þ¡¢ÅÌÎÊÄ£×ÓÈíɾ³ýµÄÊý¾Ý
LaravelÌṩÁ˺ÜÊǼòÆ ÅÌÎÊÈíɾ³ýÊý¾Ý µÄ¹¦Ð§¡£Ö»ÐèÒªÔÚÅÌÎÊÓï¾äÖмÓÉÏ withTrashed() ¼´¿É¡£
// »ñÈ¡Èíɾ³ýµÄ¹¤¾ß MyModel::withTrashed()->where('id', 1)->get(); // »ñÈ¡ËùÓеŤ¾ß£¬°üÀ¨Èíɾ³ýµÄ MyModel::withTrashed()->get(); // Ö»»ñÈ¡Èíɾ³ýµÄ¹¤¾ß MyModel::onlyTrashed()->get();
µÇ¼ºó¸´ÖÆ
Èý¡¢»Ö¸´±»Èíɾ³ýµÄÊý¾Ý
ÈôÐèÒª»Ö¸´±»Èíɾ³ýµÄÊý¾Ý£¬ÔòÐèŲÓà restore()ÒªÁì¡£
// »Ö¸´Ä³Ò»Ìõ±»Èíɾ³ýµÄÊý¾Ý MyModel::withTrashed()->find($id)->restore(); // °´Ìõ¼þ»Ö¸´ÇкÏÌõ¼þµÄÊý¾Ý MyModel::withTrashed()->where('is_visible', true)->restore();
µÇ¼ºó¸´ÖÆ
ËÄ¡¢³¹µ×ɾ³ý±»Èíɾ³ýµÄÊý¾Ý
ÈôijЩ±»Èíɾ³ýµÄÊý¾ÝÒѾ²»ÔÙÐèÒª£¬ÎÒÃÇ¿ÉÒÔͨ¹ý Ò»ÐдúÂë À´¶ÔÆä¾ÙÐÐ ³¹µ×ɾ³ý¡£
// ³¹µ×ɾ³ýijһÌõÈíɾ³ýµÄÊý¾Ý MyModel::withTrashed()->find($id)->forceDelete(); // °´Ìõ¼þ³¹µ×ɾ³ýÇкÏÌõ¼þµÄÊý¾Ý MyModel::withTrashed()->where('is_visible', true)->forceDelete();
µÇ¼ºó¸´ÖÆ
×ÛÉÏ£¬Ê¹Óà Laravel µÄÈíɾ³ýºÍ»Ö¸´Æ¬¶Ï¹¦Ð§¿ÉÒÔ´ó´óÔöÇ¿Êý¾ÝµÄ¿É»Ø¹öÐÔ£¬²¢ÇÒ²»»áÕæÕýµÄɾ³ýÊý¾Ý£¬½µµÍÎó²Ù×÷µÄΣº¦¡£Í¬Ê±£¬×ÅʵÏÖÒ²ºÜÊǼòÆÓ£¬Ö»ÐèÒªÔÚÄ£×ÓÖпªÆôÏà¹Ø¹¦Ð§¼´¿É¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel Èíɾ³ýºÍ»Ö¸´Æ¬¶Ï£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡