12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- declare(strict_types=1);
- namespace App\Model\Arts;
- use App\Model\Model;
- use Hyperf\DbConnection\Db;
- use function Hyperf\Config\config;
- class UserWalletModel extends Model
- {
- /**
- * The table associated with the model.
- *
- * @var ?string
- */
- protected ?string $table = 'user_wallet';
- protected ?string $dateFormat = 'U';
- public bool $timestamps = false;
- /**
- * 默认查询字段
- *
- * @var array|string[]
- */
- public array $select = [
- '*'
- ];
- /**
- * 获取钱包信息
- * @param int $user_id
- * @param string $field
- * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|mixed|object|string|null
- */
- public static function getOne(int $user_id, string $field = '')
- {
- //所有钱包余额
- $wallet = self::query()->where(['user_id' => $user_id])->first();
- if (!empty($field)) {
- return $wallet[$field] ?? '';
- }
- return $wallet;
- }
- /**
- * 钱包操作
- * @param int $user_id
- * @param float $money
- * @param string $remark
- * @param int $type
- * @return bool
- */
- public function change(int $user_id, float $money, string $remark = '', int $type = 3)
- {
- if (!in_array($type, [3, 4])) {
- return $this->error('余额类型错误');
- }
- $wallet = (new static())->getOne($user_id);
- if ($type == 3) {
- // 消费
- $data = [
- 'money' => bcadd($wallet['money'], (string)(-$money), 2),
- 'disburse_money' => bcadd($wallet['disburse_money'], (string)$money, 2)
- ];
- if ($data['money'] < 0) {
- return $this->error('余额不足');
- }
- $log_money = -$money;
- } else {
- // 退还
- $data = [
- 'money' => bcadd($wallet['money'], (string)$money, 2),
- 'disburse_money' => bcadd($wallet['disburse_money'], (string)(-$money), 2)
- ];
- $log_money = $money;
- }
- if (!$this->query()->where(['user_id' => $user_id, 'money' => $wallet['money']])->update($data)) {
- $this->error('操作失败');
- }
- if (!UserMoneyLogModel::query()->insert(['user_id' => $user_id, 'type' => $type, 'money' => $log_money, 'before' => $wallet['money'], 'after' => $data['money'], 'remark' => $remark, 'create_time' => time()])) {
- $this->error('记录操作失败');
- }
- return $this->success('操作成功');
- }
- }
|