BaseModel.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\common\model;
  15. use app\common\service\FileService;
  16. use think\facade\Db;
  17. use think\Model;
  18. /**
  19. * 基础模型
  20. * Class BaseModel
  21. * @package app\common\model
  22. */
  23. class BaseModel extends Model
  24. {
  25. /**
  26. * @notes 公共处理图片,补全路径
  27. * @param $value
  28. * @return string
  29. * @author 张无忌
  30. * @date 2021/9/10 11:02
  31. */
  32. public function getImageAttr($value)
  33. {
  34. return trim($value) ? FileService::getFileUrl($value) : '';
  35. }
  36. /**
  37. * @notes 公共图片处理,去除图片域名
  38. * @param $value
  39. * @return mixed|string
  40. * @author 张无忌
  41. * @date 2021/9/10 11:04
  42. */
  43. public function setImageAttr($value)
  44. {
  45. return trim($value) ? FileService::setFileUrl($value) : '';
  46. }
  47. public static function getDb(){
  48. $model = new static();
  49. return $model->db()->getTable();
  50. }
  51. /**
  52. * 批量更新字段
  53. * 获取DB 对象并赋予 模型本身的 connection 连接
  54. * @return mixed
  55. */
  56. public static function updateWhenCase($datas)
  57. {
  58. if(is_array($datas) && count($datas) > 0 ){
  59. $ids = array_keys($datas);
  60. if(is_array(reset($datas))){
  61. $fields = array_keys(reset($datas));
  62. $sql= " update ". self::getDb() ." set ";
  63. foreach($fields as $field ){
  64. $sql.= " `$field` = ( case id";
  65. foreach($datas as $id => $data ){
  66. $sql.= " when $id then ".self::stringFilter($data[$field])." ";
  67. }
  68. $sql.= " end ),";
  69. }
  70. $sql = substr($sql,0,-1);
  71. $sql.= " where id in (".implode(",",$ids).")";
  72. Db::execute($sql);
  73. }
  74. }
  75. }
  76. public static function stringFilter($string)
  77. {
  78. if(is_null($string)) {
  79. return 'null';
  80. }
  81. return "'" . str_replace("'","\'",$string) . "'";
  82. }
  83. }