请问模型关联关系中如何使用多字段条件
1. 运行环境
1). 当前使用的 Laravel 版本?
10.2.0
2. 问题描述?
用户授权策略 policy
中使用 update
方法参数中注入了目标模型,我如果想在之后的程序中复用该模型,而不想重新 find
查询,有没有解决方案?
3.补充一下代码
比如我有一个 TeamPolicy
采用自发现方式调用。
# 完整代码较长,我只贴关键部分
class TeamPolicy
{
/**
* 我想复用 update 方法参数中的 team
* 因为它在校验用户权限的时候将被首次查询
*/
public function update(User $user, Team $team): bool
{
// 如果是团队的创建者,可以修改
if ($user->id === $team->owner_id) {
return true;
}
// 如果有团队修改权限,可以修改
if (!$user->can('teams.update')) {
return false;
}
return true;
}
}
然后我在 TeamUpdate 类型中想复用它不想重新查询,请问如何绑定这个实例
final class TeamUpdate
{
readonly public TeamUpdateService $teamUpdateService;
public function __construct(Team $team)
{
# 以下这行虽然可以看到 $team 被传入实例,但其中的数据是空的
# 请问如何查询到上面授权策略注入的实例。
info('app', [$team,]);
$this->teamUpdateService = app(TeamUpdateService::class);
}
/**
* 更新团队
*
* @param null $_
* @param array{} $args
* @return Team
* @throws Throwable
* @throws ValidationException
*/
public function __invoke($_, array $args): Team
{
$input = data_get($args, 'teamUpdateInput');
info('app', [app(Team::class,Arr::only($input,['id'])),]);
$team = Team::find(data_get($input, 'id'));
/** @var User $user */
$user = auth()->user();
throw_if(!$team, GraphQLRenderException::class, '团队不存在');
$data = Arr::only($input, ['name', 'quota']);
throw_if(
isset($data['quota']) && !$user->can('teams.audit'),
GraphQLRenderException::class,
'没有权限修改团队额度'
);
return $this->teamUpdateService->handle($team, $data);
}
}
普通的策略方法返回简单的布尔值,所以很难满足一些特殊情况
策略响应可以包含更多信息,这是它的
toArray()
方法文档上判断策略响应的示例
但这些不能解决你的问题。。。