BaseModel.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/02
  6. */
  7. namespace liuniu;
  8. use think\Db;
  9. use think\Model;
  10. class BaseModel extends Model
  11. {
  12. private static $errorMsg;
  13. private static $transaction = 0;
  14. private static $DbInstance = [];
  15. const DEFAULT_ERROR_MSG = '操作失败,请稍候再试!';
  16. protected static function getDb($name,$update = false)
  17. {
  18. if(isset(self::$DbInstance[$name]) && $update == false)
  19. return self::$DbInstance[$name];
  20. else
  21. return self::$DbInstance[$name] = Db::name($name);
  22. }
  23. /**
  24. * 设置错误信息
  25. * @param string $errorMsg
  26. * @return bool
  27. */
  28. protected static function setErrorInfo($errorMsg = self::DEFAULT_ERROR_MSG,$rollback = false)
  29. {
  30. if($rollback) self::rollbackTrans();
  31. self::$errorMsg = $errorMsg;
  32. return false;
  33. }
  34. /**
  35. * 获取错误信息
  36. * @param string $defaultMsg
  37. * @return string
  38. */
  39. public static function getErrorInfo($defaultMsg = self::DEFAULT_ERROR_MSG)
  40. {
  41. return !empty(self::$errorMsg) ? self::$errorMsg : $defaultMsg;
  42. }
  43. /**
  44. * 开启事务
  45. */
  46. public static function beginTrans()
  47. {
  48. Db::startTrans();
  49. }
  50. /**
  51. * 提交事务
  52. */
  53. public static function commitTrans()
  54. {
  55. Db::commit();
  56. }
  57. /**
  58. * 关闭事务
  59. */
  60. public static function rollbackTrans()
  61. {
  62. Db::rollback();
  63. }
  64. /**
  65. * 根据结果提交滚回事务
  66. * @param $res
  67. */
  68. public static function checkTrans($res)
  69. {
  70. if($res){
  71. self::commitTrans();
  72. }else{
  73. self::rollbackTrans();
  74. }
  75. }
  76. }