Laravel 6 如何判断集合中JSON字段是否包含指定值
Laravel 集合判断JSON字段包含指定值的实现方案
单次查询场景
直接使用集合自带的filter或contains方法编写逻辑即可,注意兼容字段的返回类型:
$targetUserId = 123; // 你要检索的用户ID // 场景1:筛选出所有包含指定用户ID的集合项 $matchedItems = $collection->filter(function ($item) use ($targetUserId) { // 如果模型已经给user_id字段加了array cast,可跳过json_decode步骤 $userIdList = is_array($item->user_id) ? $item->user_id : json_decode($item->user_id, true); return in_array($targetUserId, $userIdList ?? []); }); // 场景2:只需判断集合中是否存在包含指定用户ID的项(性能更高) $hasMatched = $collection->contains(function ($item) use ($targetUserId) { $userIdList = is_array($item->user_id) ? $item->user_id : json_decode($item->user_id, true); return in_array($targetUserId, $userIdList ?? []); });
全局复用场景
可以给集合注册自定义宏,实现和Eloquent查询构造器同名的whereJsonContains方法,一劳永逸:
- 在
App\Providers\AppServiceProvider的boot方法中注册宏:
public function boot() { \Illuminate\Support\Collection::macro('whereJsonContains', function (string $field, $targetValue) { return $this->filter(function ($item) use ($field, $targetValue) { $fieldValue = data_get($item, $field); $arrayValue = is_array($fieldValue) ? $fieldValue : json_decode($fieldValue, true); return in_array($targetValue, $arrayValue ?? []); }); }); }
- 注册完成后即可直接调用,写法和Eloquent完全一致:
$matchedItems = $collection->whereJsonContains('user_id', 123);
注意事项
如果你的模型已经为user_id字段配置了array类型转换,返回的字段本身就是数组格式,可以省略json_decode步骤,直接判断即可。
内容的提问来源于stack exchange,提问作者drunkenbender
相关产品推荐
相关产品推荐

