73 lines
1.6 KiB
PHP
73 lines
1.6 KiB
PHP
|
|
<?php
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 文件功能:部门模型
|
|||
|
|
* 对应 departments 表,管理聊天室部门(办公厅 / 迎宾部 / 聊务部 / 宣传部等)
|
|||
|
|
* 一个部门下有多个职务(positions)
|
|||
|
|
*
|
|||
|
|
* @author ChatRoom Laravel
|
|||
|
|
*
|
|||
|
|
* @version 1.0.0
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
namespace App\Models;
|
|||
|
|
|
|||
|
|
use Illuminate\Database\Eloquent\Collection;
|
|||
|
|
use Illuminate\Database\Eloquent\Model;
|
|||
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||
|
|
|
|||
|
|
class Department extends Model
|
|||
|
|
{
|
|||
|
|
/**
|
|||
|
|
* 允许批量赋值的字段
|
|||
|
|
*
|
|||
|
|
* @var list<string>
|
|||
|
|
*/
|
|||
|
|
protected $fillable = [
|
|||
|
|
'name',
|
|||
|
|
'rank',
|
|||
|
|
'color',
|
|||
|
|
'sort_order',
|
|||
|
|
'description',
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 字段类型转换
|
|||
|
|
*/
|
|||
|
|
public function casts(): array
|
|||
|
|
{
|
|||
|
|
return [
|
|||
|
|
'rank' => 'integer',
|
|||
|
|
'sort_order' => 'integer',
|
|||
|
|
];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取该部门下的所有职务(按 rank 降序)
|
|||
|
|
*/
|
|||
|
|
public function positions(): HasMany
|
|||
|
|
{
|
|||
|
|
return $this->hasMany(Position::class)->orderByDesc('rank');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取部门当前所有在职用户(通过职务关联)
|
|||
|
|
*/
|
|||
|
|
public function activeMembers(): Collection
|
|||
|
|
{
|
|||
|
|
return UserPosition::query()
|
|||
|
|
->whereHas('position', fn ($q) => $q->where('department_id', $this->id))
|
|||
|
|
->where('is_active', true)
|
|||
|
|
->with(['user', 'position'])
|
|||
|
|
->get();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 按位阶倒序排列的查询范围
|
|||
|
|
*/
|
|||
|
|
public function scopeOrdered($query): void
|
|||
|
|
{
|
|||
|
|
$query->orderBy('sort_order')->orderByDesc('rank');
|
|||
|
|
}
|
|||
|
|
}
|