php - 将查询结果计数用于验证规则(即使为空)
问题描述
我已经制定了一个自定义验证规则fiveMaxThemesChoice
,其名称可以解释为在我正在构建的应用程序中将用户 ( Etudiant
) 限制为最多 5 个选择。themes
这是EtudiantsChoixTheme
我在 Eloquent 中注册选择的逻辑:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\EtudiantsChoixTheme;
class fiveMaxThemesChoice implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$choixEtudiants = EtudiantsChoixTheme::all();
foreach ($choixEtudiants as $choixEtudiant) {
$IdEtudiantOccurences = count($choixEtudiants->where('idEtudiant', auth()->user()->id));
if($IdEtudiantOccurences <= 5){
return true;
}
else{
return false;
}
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'You have already chosen a maximum of 5 themes.';
}
}
当表中至少有 1 条记录时,此方法有效。问题是当表变空时,即使表中还没有任何记录,也会返回验证错误消息,因此不是最大值 5(所以<= 5
应该是正确的)。为什么这不起作用?
我尝试过不同的语法:
$IdEtudiantOccurences = count($choixEtudiants->where('idEtudiant', auth()->user()->id)->first());
$IdEtudiantOccurences = $choixEtudiants->where('idEtudiant', auth()->user()->id)->first()->count();
$IdEtudiantOccurences = $choixEtudiants->where('idEtudiant', auth()->user()->id)->count();
当表为空时,同样的问题仍然存在。有谁知道这里可能是什么问题?欢迎任何帮助或建议
解决方案
<?php
declare(strict_types=1);
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\EtudiantsChoixTheme;
final class FiveMaxThemesChoice implements Rule
{
private const MAXIMUM_NUMBER_OF_THEMES = 5;
public function passes($attribute, $value): bool
{
$idEtudiant = auth()->user()->id;
$etudiantsQuery = EtudiantsChoixTheme::where('idEtudiant', $idEtudiant);
return $etudiantsQuery->count() <= self::MAXIMUM_NUMBER_OF_THEMES;
}
public function message(): string
{
return 'You have already chosen a maximum of 5 themes.';
}
}
而不是获取所有(EtudiantsChoixTheme::all();
)尝试直接进行查询并在它之后询问总数(EtudiantsChoixTheme::where(...)->count()
)
我从官方文档中获得了这个想法:https ://laravel.com/docs/4.2/queries
推荐阅读
- pycharm - python模块pywinauto故障排除
- android - Android 折叠工具栏不适用于 RecyclerView
- javascript - 错误消息后更新状态 - Firebase - React Native
- r - 在闪亮中,如何在文本输入中插入数学符号,以便我的 r 代码执行方程式?
- c++ - 从 Visual Studio 中间窗口调用方法 nlohmann::json::dump
- c# - MVVM Window 的新实例打破了绑定
- r - Runnin R 脚本的 VBA Shell
- javascript - 如何在我的命令中编写子命令?
- python - PyPI 如何决定包的最新版本是什么?
- python - 无服务器部署上的“资源类型无法更改”