Laravel 中如何加密 DB 查询的 collections.id 值并解决字段不存在报错
错误原因
你当前的写法在PHP层面提前执行了md5(encrypt('collections.id'))逻辑,计算得到的哈希值被直接作为字段名传入SQL查询,因此会抛出Unknown column的报错。加密操作需要在拿到数据库返回的原始查询结果后执行,不能写在查询字段参数中。
正确实现代码
你可以在查询得到结果集后,通过map方法遍历修改每一项的id字段值:
$collection = DB::table('collections') ->join('users','users.id','collections.user_id') ->select('collections.id', 'collections.name', 'collections.category_id', 'users.name as username', 'collections.price', 'collections.image') ->get() ->map(function ($item) { // 直接覆盖原始id为加密后的值 $item->id = md5(encrypt($item->id)); return $item; }) ->toArray(); return response()->json([ 'collection' => $collection, ], 200);
可选优化方案
如果你使用Eloquent模型而非DB门面查询,可以在模型中定义访问器实现自动加密:
// 在Collections模型中添加访问器 public function getIdAttribute($value) { return md5(encrypt($value)); }
定义后所有查询返回的id字段会自动完成加密,无需手动遍历处理。
内容的提问来源于stack exchange,提问作者Manlaibayar Amgalanbaatar
相关产品推荐
相关产品推荐

