<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Group extends Model
{
    use HasFactory;
    /**
     * 可批量赋值的属性
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'description',
    ];

    /**
     * 模型的启动方法
     * 注册模型事件监听器
     */
    protected static function boot()
    {
        parent::boot();

        // 监听分组删除事件
        static::deleting(function (Group $group) {
            // 将该分组的所有专用文档的 group_id 设置为 null（孤立状态）
            $group->documents()->update(['group_id' => null]);
        });
    }

    /**
     * 获取分组的所有用户
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * 获取分组的所有文档
     */
    public function documents(): HasMany
    {
        return $this->hasMany(Document::class);
    }
}
