生成code

This commit is contained in:
2025-08-14 15:50:57 +08:00
parent d90a8b05ce
commit 4c89b3999c
2 changed files with 31 additions and 0 deletions
+4
View File
@@ -140,6 +140,10 @@ class UserService
foreach ($result as &$data){
$data['customer_count'] = Customer::where('user_id', $data['id'])->count();
unset($data['password']);
unset($data['open_id']);
unset($data['tenant_key']);
unset($data['union_id']);
}
return $this->postProcess('List', $result);
+27
View File
@@ -79,4 +79,31 @@ class Customer extends Model
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
protected static function booted()
{
static::saved(function ($customer) {
if (empty($customer->code)) {
$customer->code = self::generateCustomerCode($customer);
// 使用saveQuietly避免递归调用
$customer->saveQuietly();
}
});
}
public static function generateCustomerCode($customer)
{
// 生成唯一16位code,CM+14位
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 8, 14));
$code = 'CM' . date('Ymd') .$unique;
return $code;
}
// 静默保存方法,不触发事件
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
}