如何在PHP/Laravel中捕获SQLite不存在的带引号列错误
问题:SQLite未检测到不存在的列导致查询返回空结果,而非报错
问题背景
因代码失误,Laravel生成了错误的SQL查询:
select * from "companies" where "companies"."id" = '9c54986f-8284-4da9-b826-c7a723de279b' and "companies"."deleted_at" is null and "company_id" = '9c54986f-8284-4da9-b826-c7a723de279b'
其中company_id列并不存在于companies表,但执行该查询时SQLite未报错,仅返回空结果。推测"company_id"被当作字符串字面量而非列引用;若去掉引号或添加表前缀,则会触发正确的错误提示:
Error: in prepare, no such column: company_id (1)
sqlite> select * from "companies" where "companies"."id" = '9c54986f-8284-4da9-b826-c7a723de279b' and "companies"."deleted_at" is null and "companies"."company_id" = '9c54986f-8284-4da9-b826-c7a723de279b'; Error: in prepare, no such column: companies.company_id (1)
核心疑问
能否通过Laravel或SQLite的配置解决该问题?(注:无法修改框架生成查询的方式,且已知该查询行为的原因,无需解释)
生成错误查询片段的代码实现
抽象Scope类
abstract readonly class UnlessAuthorizedScope implements Scope { public function __construct( private string $modelField, protected ?string $authorizingPermission, private string $userField, ) {} public function apply(Builder $builder, Model $model): void { if (Auth::hasUser()) { $user = Auth::user(); if ( !$this->authorizingPermission || !$user?->can($this->authorizingPermission) ) { $builder->where( $this->modelField, $user?->{$this->userField} ); } } } }
具体实现类
readonly class CurrentCompanyScope extends UnlessAuthorizedScope { public function __construct(?string $authorizingPermission = null, ?string $modelField = null) { parent::__construct( $modelField ?? "company_id", $authorizingPermission, "company_id" ); } }
模型中使用Scope
class Company extends Model { protected static function booted(): void { parent::booted(); static::addGlobalScope(new CurrentCompanyScope( CompanyPermission::ViewAll->value, // 错误点:未指定"id",保留了默认的"company_id" )); } }
内容的提问来源于stack exchange,提问作者Matteo Tassinari
相关产品推荐
相关产品推荐

