95 lines
2.7 KiB
PHP
95 lines
2.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace ywxapp\model;
|
|
|
|
use ywxapp\model\BaseModel;
|
|
|
|
use think\facade\Db;
|
|
use think\model\concern\SoftDelete;
|
|
|
|
/**
|
|
* 勋章中心
|
|
*/
|
|
class Medal extends BaseModel
|
|
{
|
|
use SoftDelete;
|
|
|
|
protected $name = 'medal';
|
|
protected $deleteTime = 'delete_at';
|
|
protected $defaultSoftDelete = 0;
|
|
|
|
// 时间戳自动写入
|
|
protected $autoWriteTimestamp = true;
|
|
protected $createTime = 'create_at';
|
|
protected $updateTime = 'update_at';
|
|
|
|
/**
|
|
* 控制器初始化(模型实例方法,非静态)
|
|
*/
|
|
protected function initialize()
|
|
{
|
|
parent::initialize();
|
|
self::ensureSchema();
|
|
}
|
|
|
|
/**
|
|
* 授予勋章(幂等:同一用户同一勋章仅记录一次)
|
|
* @return array [bool $ok, string $msg]
|
|
*/
|
|
public static function grant(int $uid, int $medalId): array
|
|
{
|
|
self::ensureSchema(); // 确保 user_medal 关联表已就绪(静态入口也可能在未实例化模型时被调用)
|
|
if ($uid <= 0) {
|
|
return [false, '用户未登录'];
|
|
}
|
|
$medal = self::where('id', $medalId)->where('status', 1)->find();
|
|
if (!$medal) {
|
|
return [false, '勋章不存在或未启用'];
|
|
}
|
|
|
|
$exists = Db::name('member_medal')
|
|
->where('uid', $uid)
|
|
->where('medal_id', $medalId)
|
|
->find();
|
|
if ($exists) {
|
|
return [true, '已拥有该勋章'];
|
|
}
|
|
|
|
Db::name('member_medal')->insert([
|
|
'uid' => $uid,
|
|
'medal_id' => $medalId,
|
|
'create_at' => time(),
|
|
]);
|
|
return [true, '恭喜获得勋章:' . $medal->title];
|
|
}
|
|
|
|
/**
|
|
* 取某用户拥有的勋章列表(含勋章信息)
|
|
*/
|
|
public static function getUserMedals(int $uid): array
|
|
{
|
|
self::ensureSchema(); // 确保 user_medal 关联表已就绪(静态入口也可能在未实例化模型时被调用)
|
|
if ($uid <= 0) {
|
|
return [];
|
|
}
|
|
return Db::name('member_medal')
|
|
->alias('um')
|
|
->join('medal m', 'm.id = um.medal_id')
|
|
->where('um.uid', $uid)
|
|
->where('m.delete_at', 0)
|
|
->field('m.id,m.title,m.image,m.description,um.create_at')
|
|
->order('um.create_at', 'desc')
|
|
->select()
|
|
->toArray();
|
|
}
|
|
|
|
/**
|
|
* 表自愈:确保勋章相关表(medal / member_medal)已就绪。
|
|
*/
|
|
public static function ensureSchema(): void
|
|
{
|
|
$prefix = BaseModel::currentPrefix();
|
|
BaseModel::ensureTableFromInstall($prefix, 'medal');
|
|
BaseModel::ensureTableFromInstall($prefix, 'member_medal');
|
|
}
|
|
} |