본문 바로가기

개발/laravel

Laravel의 whereJsonContains 메서드: JSON 데이터 필터링의 강력한 도구

반응형

 

Laravel은 PHP 프레임워크 중 하나로, 웹 애플리케이션 개발을 더 쉽게 만들어주는 다양한 기능을 제공합니다. 그중 하나가 whereJsonContains 메서드로, JSON 필드에서 특정 값을 필터링하는 데 유용하게 사용됩니다. 이 글에서는 whereJsonContains의 사용법과 실제 예시를 통해 그 기능을 살펴보겠습니다.

1. whereJsonContains 메서드란?

whereJsonContains는 Eloquent 쿼리 빌더에서 사용되는 메서드로, 데이터베이스에서 JSON 열 안에 특정 값이 포함되어 있는지를 확인하는 데 사용됩니다. 이 메서드는 주로 JSON 형식으로 저장된 데이터가 포함된 필드를 조회할 때 유용합니다.

2. 사용법

whereJsonContains 메서드는 다음과 같은 형태로 사용됩니다:

ModelName::whereJsonContains('json_column_name', 'value')->get();
 

여기서 json_column_name은 JSON 데이터를 저장하는 열의 이름이고, 'value'는 검색하려는 값입니다.

3. 예시

아래는 간단한 예시를 통해 whereJsonContains의 사용법을 설명합니다. 가정해보면, 사용자가 저장된 products 테이블에 여러 속성이 있는 JSON 데이터를 갖고 있다고 하겠습니다.

예제 데이터 구조

[
  {
    "id": 1,
    "name": "Laptop",
    "tags": ["electronics", "computers"]
  },
  {
    "id": 2,
    "name": "Shoes",
    "tags": ["fashion", "footwear"]
  },
  {
    "id": 3,
    "name": "Smartphone",
    "tags": ["electronics", "mobile"]
  }
]

사용 예시

위의 JSON 데이터에서 tags 배열에 "electronics"라는 태그가 포함된 모든 제품을 조회하고 싶다고 가정해 보겠습니다.

$electronicsProducts = Product::whereJsonContains('tags', 'electronics')->get();
 

이 쿼리는 tags 배열에 "electronics"가 포함된 모든 제품을 반환합니다. 결과적으로 LaptopSmartphone이 조회될 것입니다.

4. 복합 조건 사용하기

whereJsonContains를 다른 조건과 조합하여 사용할 수도 있습니다. 예를 들어, 태그가 electronics이고 가격이 500달러 이상인 제품을 찾고 싶다면 다음과 같이 쓸 수 있습니다.

php
코드 복사
$filteredProducts = Product::whereJsonContains('tags', 'electronics') ->where('price', '>=', 500) ->get();
$filteredProducts = Product::whereJsonContains('tags', 'electronics')
                          ->where('price', '>=', 500)
                          ->get();​

 

whereJsonContains 메서드는 Laravel에서 JSON 형식의 데이터를 효율적으로 필터링할 수 있는 강력한 도구입니다. 이 메서드를 사용하면 복잡한 JSON 데이터를 쉽게 검색하고, 조건에 맞는 데이터를 효과적으로 조회할 수 있습니다.

이러한 기능은 데이터베이스 구조가 복잡해질수록 더욱 유용하게 활용될 수 있습니다. 

 

https://laravel.com/docs/11.x/queries#json-where-clauses

 

Laravel - The PHP Framework For Web Artisans

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

laravel.com

 

반응형

'개발 > laravel' 카테고리의 다른 글

라라벨에서 커스텀 helper 등록하기  (2) 2024.10.07
라라벨 Sail 설정 가이드  (0) 2023.10.10
[Laravel] log permission denied  (0) 2023.07.11
[laravel5.5] 302 redirect status code  (0) 2022.09.06
[laravel 5.5/QueryBuilder] SubQuery  (0) 2022.08.30