ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# :-: 编写Model ## 编写model 这里没有进行约束,只是正常的 CURD 操作,以及表多对多关联的关系说明。虽然只提供了基础操作,但是还是希望不要直接使用 Model在你的项目中,下面会提到用什么方式访问 ### permission model ```php namespace think\permissions\model; use think\Model; class Permissions extends Model { // 为了可控性,这里只从配置文件读取表名 public function initialize() { parent::initialize(); // TODO: Change the autogenerated stub $this->name = config('permissions.table.permission'); } public function getPermissionBy($permission_id) { return self::get($permission_id); } public function deleteBy($permission_id) { return $this->getPermissionBy($permission_id)->delete(); } public function updateBy(int $id, array $data) { return self::where('id', $id)->update($data); } public function store(array $data) { $this->data($data); return $this->save(); } public function getPermissionByModuleAnd($module, $controller, $action) { return $this->where([ 'module' => $module, 'controller' => $controller, 'action' => $action, ])->find(); } } ``` ### role model ```php namespace think\permissions\model; use think\Model; class Roles extends Model { public function initialize() { parent::initialize(); // TODO: Change the autogenerated stub $this->name = config('permissions.table.role'); } public function permissions() { return $this->belongsToMany(config('permissions.model.permission'), config('permissions.table.role_has_permissions'), 'permission_id', 'role_id'); } public function users() { return $this->belongsToMany(config('permissions.model.user'), 'user_has_roles', 'uid', 'role_id'); } public function getRoleBy($role_id) { return $this->where('id', $role_id)->find(); } public function getPermissions($role_id, $full = true) { return $full ? $this->getRoleBy($role_id)->permissions : $this->getRoleBy($role_id)->permissions()->column('permission_id'); } public function attachPermissions($roles_id, $permissions = null) { return $this->getRoleBy($roles_id)->permissions()->attach($permissions); } public function detachPermissions($role_id, $permissions = null) { return $this->getRoleBy($role_id)->permissions()->detach($permissions); } public function detachUsers($id, $users = null) { return $this->getRoleBy($id)->users()->detach($users); } public function deleteBy($role_id) { return $this->getRoleBy($role_id)->delete(); } public function updateBy($id, array $data) { return self::where('id', $id)->update($data); } public function store(array $data) { $this->data($data); return $this->save(); } } ```