// +---------------------------------------------------------------------- namespace ywxapp\model; use think\model\concern\SoftDelete; use ywxapp\model\BaseModel; /** * BackendRole 类 * * @author ywxapp */ class BackendRole extends BaseModel { use SoftDelete; // 设置表名(think-orm 4.0:name 不带前缀,自动拼 wxapp_) protected $name = 'backend_role'; // 设置主键 protected $pk = 'id'; // 自动时间戳 protected $autoWriteTimestamp = 'int'; protected $createTime = 'create_at'; protected $updateTime = 'update_at'; protected $deleteTime = 'delete_at'; // 隐藏字段 protected $hidden = ['password', 'delete_at']; // 只读字段 protected $readonly = ['id']; // 角色拥有的用户 public function admins() { return $this->belongsToMany(BackendAdmin::class, BackendRoleAccess::class, 'admin_id', 'role_id'); } /** * 角色 → 权限字符串(通过 role_permissions 表) */ public function powers() { // 返回的是 permission 字符串列表(不是 Menu 模型) return $this->belongsToMany(BackendPower::class, BackendRolePower::class, 'power_id', 'role_id')->field('power_id'); } // 【推荐】角色 → 菜单模型(通过中间表 role_permissions 关联 menus) public function menus() { return $this->belongsToMany(BackendPower::class, BackendRolePower::class, 'power_id', 'role_id', 'permission'); } /** * 表结构自愈:建表 + 关键列兜底(install.sql 为事实源)。 * 查询/写入前调用,避免老库缺表导致 1146。 */ public static function ensureSchema(): void { BaseModel::ensureTableFromInstall(BaseModel::currentPrefix(), 'backend_role'); } }