ModelExtend.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace addons\exam\traits;
  3. use think\Db;
  4. /**
  5. * Trait ModelExtend
  6. * 自封装的模型扩展
  7. * 基本来源于Laravel操作
  8. * by zgc
  9. */
  10. trait ModelExtend
  11. {
  12. /**
  13. * 获取对象,空直接抛错
  14. *
  15. * @param integer $pk 主键
  16. * @param string $message 提示的错误信息
  17. * @param array $with 预加载
  18. */
  19. public static function findOrFail(int $pk, string $message = '数据不存在', $with = []): self
  20. {
  21. if (!$pk) {
  22. fail('缺少主键信息');
  23. }
  24. $model = $with ? self::with($with)->find($pk) : self::get($pk);
  25. if (!$model) {
  26. fail($message);
  27. }
  28. return $model;
  29. }
  30. /**
  31. * 更新或创建
  32. * @param array $attributes 条件
  33. * @param array $values 值
  34. * @return mixed
  35. */
  36. public static function updateOrCreate(array $attributes, array $values = [], string $type = 'count')
  37. {
  38. $self = new static();
  39. // $model = $self->where($attributes)->find();
  40. $model = $self::get($attributes);
  41. if ($model) {
  42. $model->data($values, true);
  43. } else {
  44. $model = new static();
  45. $model->data($values);
  46. }
  47. $count = $model->allowField(true)->save();
  48. if ($type == 'count') {
  49. return $count;
  50. }
  51. return $model;
  52. }
  53. /**
  54. * 批量插入或更新
  55. * @param array $values
  56. */
  57. public static function upsert(array $values, $pk = 'id')
  58. {
  59. Db::transaction(function () use ($values, $pk) {
  60. collection($values)->each(function ($item) use ($pk) {
  61. $id = isset($item[$pk]) ? $item[$pk] : 0;
  62. self::updateOrCreate(
  63. [$pk => $id],
  64. $item
  65. );
  66. });
  67. });
  68. }
  69. /**
  70. * 只取模型部分key数据
  71. * @param array $keys
  72. * @return array
  73. */
  74. public function only(array $keys): array
  75. {
  76. // return only_keys($this->toArray(), $keys);
  77. $result = [];
  78. foreach ($this->toArray() as $k => $value) {
  79. if (in_array($k, $keys)) {
  80. $result[$k] = $value;
  81. }
  82. }
  83. return $result;
  84. }
  85. /**
  86. * 隐藏模型部分key数据
  87. * @param array $keys
  88. * @return array
  89. */
  90. public function makeHidden(array $keys): array
  91. {
  92. // return only_keys($this->toArray(), $keys);
  93. $result = [];
  94. foreach ($this->toArray() as $k => $value) {
  95. if (in_array($k, $keys)) {
  96. unset($value[$k]);
  97. $result[$k] = $value;
  98. }
  99. }
  100. return $result;
  101. }
  102. }