6
0
Fork 0
jiqu-library-server/app/Models/UserInfo.php

139 lines
2.9 KiB
PHP

<?php
namespace App\Models;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class UserInfo extends Model
{
use HasDateTimeFormatter;
public const GENDER_UNKNOWN = 'unknown'; // 未知
public const GENDER_MALE = 'male'; // 男性
public const GENDER_FEMALE = 'female'; // 女性
/**
* @var string
*/
protected $primaryKey = 'user_id';
/**
* @var bool
*/
public $incrementing = false;
/**
* @var array
*/
protected $attributes = [
'gender' => self::GENDER_UNKNOWN,
];
/**
* @var array
*/
protected $fillable = [
'inviter_id',
'nickname',
'avatar',
'gender',
'birthday',
'depth',
'path',
'growth_value',
'real_inviter_id',
'is_company'
];
/**
* @var array
*/
protected $casts = [
'birthday' => 'date',
];
public static $genderTexts = [
self::GENDER_UNKNOWN => '未知',
self::GENDER_MALE => '男性',
self::GENDER_FEMALE => '女性',
];
/**
* {@inheritdoc}
*/
protected static function booted()
{
parent::saving(function ($userInfo) {
// 如果没有邀请码,则自动分配邀请码
if ($userInfo->code === null) {
do {
$userInfo->code = strtolower(Str::random(6));
} while (static::where('code', $userInfo->code)->exists());
} elseif ($userInfo->isDirty('code')) {
$userInfo->code = strtolower($userInfo->code);
}
});
}
/**
* 用户
*
* @return void
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* 获取此用户的邀请人信息
*/
public function inviterInfo()
{
return $this->belongsTo(UserInfo::class, 'inviter_id');
}
/**
* 获取此用户的真实邀请人信息
*/
public function realInviterInfo()
{
return $this->belongsTo(UserInfo::class, 'real_inviter_id');
}
/**
* 获取此用户的所有父级ID
*
* @return array
*/
public function getParentIdsAttribute(): array
{
if ($path = trim($this->path, '-')) {
return explode('-', $path);
}
return [];
}
public function getRealParentIdsAttribute(): array
{
$rpids = (array) $this->realInviterInfo?->parent_ids;
if ($this->real_inviter_id) {
array_push($rpids, $this->real_inviter_id);
}
return $rpids;
}
/**
* 获取完整的邀请路径
*
* @return string
*/
public function getFullPathAttribute(): string
{
return Str::finish($this->path.$this->getKey(), '-');
}
}