init
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace plugin\admin\app\repository;
|
||||
|
||||
use plugin\admin\app\model\Base;
|
||||
use plugin\admin\app\repository\exception\EntityNotFoundException;
|
||||
|
||||
abstract class BaseRepository
|
||||
{
|
||||
protected Base $model;
|
||||
|
||||
public static abstract function new(): BaseRepository;
|
||||
|
||||
/**
|
||||
* 返回带数据权限的查询构建器
|
||||
*/
|
||||
public function scopedQuery()
|
||||
{
|
||||
return $this->model->newQuery()->withDataPermission();
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过ID查找记录(带数据权限),找不到则抛异常
|
||||
* @throws EntityNotFoundException
|
||||
*/
|
||||
public function findWithPermission(int $id)
|
||||
{
|
||||
$record = $this->scopedQuery()->find($id);
|
||||
if (!$record) {
|
||||
throw new EntityNotFoundException('记录不存在');
|
||||
}
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过ID批量删除(带数据权限)
|
||||
*/
|
||||
public function deleteWithPermission(array $ids): void
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return;
|
||||
}
|
||||
$primaryKey = $this->model->getKeyName();
|
||||
$this->scopedQuery()->whereIn($primaryKey, $ids)->each(function ($model) {
|
||||
$model->delete();
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user