laravel »Ö¸´Èíɾ³ý
laravelÊÇÒ»¿îºÜÊÇÊ¢ÐеÄphp¿ò¼Ü£¬ËüÌṩÁËÐí¶àÀû±ãµÄ¹¦Ð§À´¼ÓËÙ¿ª·¢ÕߵĿª·¢ËÙÂÊ¡£ÆäÖÐÒ»¸öºÜÊÇÖ÷ÒªµÄ¹¦Ð§ÊÇÈíɾ³ý£¬ËüÄܹ»ÈÃÎÒÃǽ«Êý¾Ý¿âÖеļͼ±ê¼ÇΪÒÑɾ³ý£¬µ«²¢²»»áÕæÕý´ÓÊý¾Ý¿âÖÐɾ³ýÕâЩ¼Í¼¡£ÕâÖÖÒªÁì¹ØÓÚ±£´æÊý¾ÝÀúÊ·¼Í¼ºÍ±ÜÃâÒâÍâɾ³ýºÜÊÇÓÐÓ᣿ÉÊÇ£¬ÓÐʱ¼äÎÒÃÇÐèÒª»Ö¸´ÕâЩÒÑɾ³ýµÄ¼Í¼£¬ÄÇôÔÚlaravelÖиÃÔõÑùʵÏÖÄØ£¿
Ê×ÏÈ£¬ÎÒÃÇÐèҪȷÈÏÎÒÃǵÄÊý¾ÝÄ£×ÓʹÓÃÁËÈíɾ³ý¹¦Ð§¡£Í¨³££¬ÎÒÃÇ¿ÉÒÔÔÚÄ£×ÓÖÐʹÓÃSoftDeletes traitÀ´¿ªÆôÈíɾ³ý¹¦Ð§¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔÚUserÄ£×ÓÖÐÕâÑùд£º
use IlluminateDatabaseEloquentModel; use IlluminateDatabaseEloquentSoftDeletes; class User extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
µÇ¼ºó¸´ÖÆ
ÕâÑù¾Í¿ÉÒÔÔÚ¸ÃÄ£×ÓÖÐʹÓÃÈíɾ³ý¹¦Ð§ÁË¡£ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔÔÚÊý¾Ý¿âÖÐÖ´ÐÐɾ³ý²Ù×÷£¬ÀýÈ磺
$user = User::find(1); $user->delete();
µÇ¼ºó¸´ÖÆ
Íê³ÉÕâ¸ö²Ù×÷ºó£¬ÎÒÃÇ¿ÉÒÔʹÓÃwithTrashedÒªÁìÀ´»ñÈ¡±»Èíɾ³ýµÄÓû§¼Í¼¡£ÀýÈ磺
$deletedUsers = User::withTrashed() ->whereNotNull('deleted_at') ->get();
µÇ¼ºó¸´ÖÆ
ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔ»á¼ûÿ¸öÈíɾ³ýµÄÓû§¼Í¼µÄdeleted_atÊôÐÔ£¬ÒÔÏàʶÆäɾ³ýʱ¼ä¡£ÈôÊÇÎÒÃÇÐèÒª»Ö¸´Ä³¸öÒÑɾ³ýµÄÓû§¼Í¼£¬ÎÒÃÇ¿ÉÒÔʹÓÃrestoreÒªÁì¡£ÀýÈ磬¼ÙÉèÎÒÃÇÒª»Ö¸´idΪ1µÄÓû§¼Í¼£¬ÎÒÃÇ¿ÉÒÔÕâÑùд£º
µã»÷ÏÂÔØ¡°àËÃûÌÃÊý¾Ý»Ö¸´¾Þ½³¡±£»
$user = User::withTrashed() ->where('id', 1) ->first(); $user->restore();
µÇ¼ºó¸´ÖÆ
Ö÷ÒªµÄÊÇÒªÒâʶµ½£¬ÔÚ¾ÙÐлָ´²Ù×÷ʱ£¬ÎÒÃÇÐèÒªÏȽ«Èíɾ³ýµÄÊý¾ÝÄ£×ÓʹÓÃwithTrashedÒªÁì´ÓÊý¾Ý¿âÖмìË÷³öÀ´¡£ÕâÊÇÓÉÓÚΨÓб»Èíɾ³ýµÄÊý¾Ý²Å¿ÉÒÔ±»»Ö¸´¡£
³ý´ËÖ®Í⣬ÎÒÃÇ»¹¿ÉÒÔʹÓÃrestoreOrFailÒªÁ죬ËüÄܹ»ÔÚ»Ö¸´Ê§°ÜʱÅ׳öÒì³£¡£ÀýÈ磺
$user = User::withTrashed() ->where('id', 1) ->first(); try { $user->restoreOrFail(); } catch (Exception $e) { // »Ö¸´Ê§°Ü }
µÇ¼ºó¸´ÖÆ
ÁíÍâÐèҪעÖصÄÊÇ£¬ÈôÊÇÎÒÃÇÕýÔÚʵÑé»Ö¸´Ò»¸ö²»±£´æµÄÈíɾ³ýÊý¾ÝÄ£×Ó£¬½«»áÒý·¢Ò»¸öÒì³£¡£Òò´Ë£¬ÎªÁË×èÖ¹ÕâÖÖÇéÐΣ¬ÎÒÃÇ¿ÉÒÔʹÓÃrestoreOnFailÒªÁ죬Ëü»áÔÚ»Ö¸´Ê§°Üʱ·µ»Øfalse¡£ÀýÈ磺
$user = User::withTrashed() ->where('id', 1) ->first(); if (!$user->restoreOnFail()) { // »Ö¸´Ê§°Ü }
µÇ¼ºó¸´ÖÆ
×ܵÄÀ´Ëµ£¬Ê¹ÓÃLaravel»Ö¸´Èíɾ³ýºÜÊǼòÆÓ¡£Ö»ÐèҪƾ֤ÉÏÊö°ì·¨Ö´Ðм´¿É¡£¿ÉÊÇ£¬ÎÒÃÇÐèҪעÖØһЩϸ½Ú£¬ÀýÈçʹÓÃwithTrashedÒªÁìÀ´»ñÈ¡ÒÑɾ³ýµÄ¼Í¼¡¢Ê¹ÓÃrestoreÒªÁìÀ´»Ö¸´Èíɾ³ýµÄ¼Í¼µÈ¡£ÕâЩ¶¼ÊÇÔÚLaravelÖÐʹÓÃÈíɾ³ý¹¦Ð§Ê±ÐèҪעÖصĵط½¡£
×ܽáһϣ¬»Ö¸´Èíɾ³ýµÄ°ì·¨ÈçÏ£º
È·ÈÏÊý¾ÝÄ£×ÓÒÑ¿ªÆôÈíɾ³ý¹¦Ð§
ʹÓÃwithTrashedÒªÁì»ñÈ¡Èíɾ³ýµÄ¼Í¼
ʹÓÃrestoreÒªÁì»Ö¸´Èíɾ³ýµÄ¼Í¼
¿ÉÒÔʹÓÃrestoreOrFailÒªÁìÀ´Å׳öÒì³££¬»òÕßʹÓÃrestoreOnFailÒªÁìÀ´·µ»Øfalse£¬ÒÔÈ·±£»Ö¸´²Ù×÷ÀÖ³É
Ï£ÍûÕâƪÎÄÕÂÄܹ»×ÊÖú¶ÁÕ߸üºÃµØÏàʶLaravelÖÐÔõÑù»Ö¸´Èíɾ³ý¡£
ÒÔÉϾÍÊÇlaravel »Ö¸´Èíɾ³ýµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡