ThinkPHPÖеÄÊÂÎñÔõôʹÓÃ
Ò»¡¢ÊÂÎñµÄ¿´·¨
Ò»¸öÊÂÎñÊÇÓÉһϵÁвÙ×÷×é³ÉµÄ£¬ÕâЩ²Ù×÷±»×÷Ϊһ¸öÕûÌåÖ´ÐУ¬Ö»ÓÐËùÓÐÀֳɻòËùÓÐʧ°Ü¡£Í¨ÀýÓ¦Óó¡¾°ÖУ¬ÊÂÎñÒ»Ñùƽ³£ÓÃÓÚÊý¾Ý¿â²Ù×÷£¬ÈçÊý¾Ý²åÈë¡¢¸üкÍɾ³ý¡£Ê¹ÓÃÊÂÎñ¿ÉÒÔÈ·±£Êý¾Ý¿âµÄÍêÕûÐÔºÍÒ»ÖÂÐÔ£¬´Ó¶ø×èÖ¹Êý¾Ý¹ýʧºÍ·×ÆçÖµı¬·¢¡£
ÔÚÊý¾Ý¿âµÄ»ù±¾²Ù×÷ÖУ¬SQLÓï¾ä¿ÉÒÔ×ÔÁ¦Ö´ÐУ¬Ò²¿ÉÒÔÓëÆäËûSQLÓï¾ä×÷Ϊһ¸öÊÂÎñÖ´ÐС£ÈôÊÇÒ»¸öÊÂÎñ±»Ö´ÐÐʱ±¬·¢¹ýʧ£¬ÄÇôÊÂÎñÖÐËùÓеIJÙ×÷¶¼½«±»»Ø¹ö£¬¼´ÊÂÎñÖеÄËùÓвÙ×÷¶¼±»×÷·Ï£¬Êý¾Ý¿âµÄ״̬»Øµ½Ö´ÐÐÊÂÎñ֮ǰµÄ״̬¡£¶øÈôÊÇÊÂÎñÀÖ³ÉÖ´ÐУ¬ÔòËùÓÐÐ޸IJÙ×÷½«±»ÓÀÊÀµØÉúÑÄÔÚÊý¾Ý¿âÖС£
¶þ¡¢ThinkPHPÖÐÊÂÎñµÄʹÓÃÒªÁì
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
ÔÚThinkPHPÖУ¬ÊÂÎñ¿ÉÒÔºÜÀû±ãµØʹÓá£ÏÂÃæÎÒÃǽ«ÏÈÈÝÊÂÎñµÄ¿ªÆô¡¢ÊÂÎñ»Ø¹öºÍÊÂÎñÌá½»µÈ²Ù×÷¡£
¿ªÆôÊÂÎñ£¨startTrans£©
ThinkPHPÖУ¬¿ÉʹÓÃÄ£×ÓÀàµÄstartTransÒªÁ쿪ÆôÒ»¸öÊÂÎñ¡£Õâ¸öÒªÌå»á×Ô¶¯¿ªÆôÒ»¸öÊÂÎñ£¬²¢½«Ä¿½ñ²Ù×÷Á÷³Ì¼ÓÈëÐÐÁУ¬ÒÔ±¸Ìá½»»ò»Ø¹öÊÂÎñʱʹÓá£
ÏÂÃæÊÇÒ»¸ö¿ªÆôÊÂÎñµÄʾÀý´úÂ룺
$model = new Model(); $model->startTrans();
µÇ¼ºó¸´ÖÆ
»Ø¹öÊÂÎñ£¨rollback£©
ÈôÊÇÔÚÊÂÎñÖ´ÐÐÀú³ÌÖб¬·¢¹ýʧ£¬ÐèÒª×÷·ÏËùÓÐÒѾִÐеIJÙ×÷£¬¿ÉÒÔʹÓÃÄ£×ÓÀàµÄrollbackÒªÁìÀ´ÊµÏÖ£¬¸ÃÒªÁ콫Õë¶ÔÄ¿½ñÄ£×ÓÖеIJÙ×÷Á÷³Ì¾ÙÐлعö²Ù×÷¡£
ÏÂÃæÊÇÒ»¸ö»Ø¹öÊÂÎñµÄʾÀý´úÂ룺
try { // Ö´ÐÐһЩÊý¾Ý¿â²Ù×÷ $model->commit(); } catch (\Exception $e) { // ²Ù×÷ʧ°Üʱ£¬»Ø¹öÊÂÎñ $model->rollback(); }
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
Ìá½»ÊÂÎñ£¨commit£©
µ±ÊÂÎñ²Ù×÷ËùÓÐÖ´ÐÐÀֳɲ¢ÇÒÒѾ֪×ãÌá½»Ìõ¼þʱ£¬ÎÒÃÇÐèҪʹÓÃcommitÒªÁì¶ÔÊÂÎñ¾ÙÐÐÌá½»£¬¸ÃÒªÁ콫¶ÔÄ¿½ñÄ£×ÓÖеIJÙ×÷Á÷³Ì¾ÙÐÐÌá½»²Ù×÷¡£
ÏÂÃæÊÇÒ»¸öÌá½»ÊÂÎñµÄʾÀý´úÂ룺
try { // Ö´ÐÐһЩÊý¾Ý¿â²Ù×÷ $model->commit(); } catch (\Exception $e) { // ²Ù×÷ʧ°Üʱ£¬»Ø¹öÊÂÎñ $model->rollback(); }
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
Èý¡¢ÊÂÎñµÄ×¢ÖØÊÂÏî
ÔÚʹÓÃÊÂÎñ²Ù×÷ʱÐèҪעÖØÒÔϼ¸¸öÎÊÌ⣺
ÊÂÎñÔÚʹÓÃÀú³ÌÖÐҪôËùÓÐÀֳɣ¬ÒªÃ´ËùÓÐʧ°Ü£¬Òò´ËÐèÒª¸ñÍâСÐĺÍÉóÉ÷£¬×èÖ¹·ºÆð¹ýʧµÄ²Ù×÷¡£
²Ù×÷¹ýʧʱ±ØÐè»Ø¹öÊÂÎñ£¬²»È»»á·ºÆðÊý¾Ý·×ÆçÖµÄÇéÐΡ£
ÊÂÎñ²Ù×÷ÊôÓÚ¸ßΣ²Ù×÷£¬ÐèҪСÐÄʹÓã¬×èÖ¹ÓÉÓÚ²»Ð¡ÐIJÙ×÷µ¼ÖÂÊý¾Ý¹ýʧ»òÕßɥʧ¡£
ÒÔÉϾÍÊÇThinkPHPÖеÄÊÂÎñÔõôʹÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡