Model
Model 只声明表映射、类型转换、访问器与关联。不在 Model 里写业务流程、不调 Service、不直接对外返回业务结果——查询与写入由 Repository 完成。
声明什么
以 app\model\system\Role 为例:
php
namespace app\model\system;
use core\base\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class Role extends Model
{
use SoftDeletes;
protected $table = 'roles';
protected $casts = [
'data_scope' => 'integer',
'is_system' => 'boolean',
'status' => 'integer',
'sort' => 'integer',
];
protected $appends = ['status_text', 'data_scope_text', 'is_system_text'];
public function admins(): BelongsToMany
{
return $this->belongsToMany(Admin::class, 'admin_roles', 'role_id', 'admin_id')->withTimestamps();
}
public function menus(): BelongsToMany
{
return $this->belongsToMany(Menu::class, 'role_menus', 'role_id', 'menu_id')->withTimestamps();
}
}边界
| 可以 | 不要 |
|---|---|
$table、$casts、$hidden、$appends | 校验请求、抛业务文案给前端 |
关联方法(belongsTo / hasMany 等) | 事务、afterCommit、清缓存 |
派生展示字段(如 status_text) | 权限判断、数据权限过滤(那是 Repository 的 query()) |
业务规则放在 Service;带数据权限的读写放在 Repository。