123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace addons\exam\traits;
- use think\Db;
- trait ModelExtend
- {
-
- public static function findOrFail(int $pk, string $message = '数据不存在', $with = []): self
- {
- if (!$pk) {
- fail('缺少主键信息');
- }
- $model = $with ? self::with($with)->find($pk) : self::get($pk);
- if (!$model) {
- fail($message);
- }
- return $model;
- }
-
- public static function updateOrCreate(array $attributes, array $values = [], string $type = 'count')
- {
- $self = new static();
-
- $model = $self::get($attributes);
- if ($model) {
- $model->data($values, true);
- } else {
- $model = new static();
- $model->data($values);
- }
- $count = $model->allowField(true)->save();
- if ($type == 'count') {
- return $count;
- }
- return $model;
- }
-
- public static function upsert(array $values, $pk = 'id')
- {
- Db::transaction(function () use ($values, $pk) {
- collection($values)->each(function ($item) use ($pk) {
- $id = isset($item[$pk]) ? $item[$pk] : 0;
- self::updateOrCreate(
- [$pk => $id],
- $item
- );
- });
- });
- }
-
- public function only(array $keys): array
- {
-
- $result = [];
- foreach ($this->toArray() as $k => $value) {
- if (in_array($k, $keys)) {
- $result[$k] = $value;
- }
- }
- return $result;
- }
-
- public function makeHidden(array $keys): array
- {
-
- $result = [];
- foreach ($this->toArray() as $k => $value) {
- if (in_array($k, $keys)) {
- unset($value[$k]);
- $result[$k] = $value;
- }
- }
- return $result;
- }
- }
|