This commit is contained in:
73
app/Scope/CompanyScope.php
Executable file
73
app/Scope/CompanyScope.php
Executable file
@ -0,0 +1,73 @@
|
||||
<?php
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2024/12/24
|
||||
* Time: 下午3:19
|
||||
* Description:
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Scope;
|
||||
|
||||
use App\Context\QueueContext;
|
||||
use App\Context\UserContext;
|
||||
use App\Utils\TableUtils;
|
||||
use Exception;
|
||||
use Hyperf\Database\Model\Builder;
|
||||
use Hyperf\Database\Model\Model;
|
||||
use Hyperf\Database\Model\Scope;
|
||||
use Hyperf\Di\Annotation\Inject;
|
||||
use Hyperf\Redis\Redis;
|
||||
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2025/5/7
|
||||
* Time: 下午4:38
|
||||
* Description: 作用域类,用于限制查询结果为当前公司、供应商的记录。
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
class CompanyScope implements Scope
|
||||
{
|
||||
use TableUtils;
|
||||
|
||||
#[Inject]
|
||||
protected Redis $redis;
|
||||
|
||||
/**
|
||||
* 将当前用户所属公司的条件应用于查询构建器。
|
||||
*
|
||||
* @param Builder $builder 查询构建器实例。
|
||||
* @param Model $model 模型实例,通常是想要应用作用域的模型。
|
||||
* @return Builder 应用了作用域条件的查询构建器实例。
|
||||
* @throws Exception
|
||||
*/
|
||||
public function apply(Builder $builder, Model $model): Builder
|
||||
{
|
||||
// 尝试从上下文中获取当前用户信息
|
||||
$user = QueueContext::getUser() ?? UserContext::getCurrentUser();
|
||||
$company = $user['company'];
|
||||
// 如果没有找到用户信息,则不应用任何条件,直接返回查询构建器
|
||||
if (!$user || !$company) {
|
||||
return $builder;
|
||||
}
|
||||
|
||||
// 如果存在 company_id,应用企业作用域
|
||||
if (!empty($companyId = $company['id'] ?? null)) {
|
||||
return self::hasColumn($model, 'company_id')
|
||||
? $builder->where($model->getTable() . '.company_id', $companyId)
|
||||
: $builder;
|
||||
}
|
||||
|
||||
return $builder;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user