Skip to content

how to check if a JSONB column contains a value -- CONTAINS? #253

@tacman

Description

@tacman

I'm sure this is simple, I'll update the docs once I know how to do it. A simple query:

            $qb = $this->articleRepository->createQueryBuilder('article');
            $qb
                ->andWhere('CONTAINS(article.tagValues, :tagValue) = TRUE')
                ->setParameter('tagValue', $tagValue)
                ->setMaxResults($limit);
            ;

tagValues is a JSON column

    #[ORM\Column(type: Types::JSON,  nullable: true, options: ['jsonb' => true])]
    private ?array $tagValues = null;
/c db:run "select tag_values from article limit 1"
 ----------------------------- 
  tag_values                   
 ----------------------------- 
  ["California", "Rob Bonta"]  
 ----------------------------- 

The SQL generated:

SELECT a0_.headline AS headline_0, a0_.summary AS summary_1, a0_.thumbnail_url AS thumbnail_url_2, a0_.url AS url_3, a0_.code AS code_4, a0_.bing AS bing_5, a0_.date_published AS date_published_6, a0_.bing_about AS bing_about_7, a0_.countries AS countries_8, a0_.tags AS tags_9, a0_.tag_count AS tag_count_10, a0_.tag_values AS tag_values_11, a0_.media_id AS media_id_12, a0_.category_id AS category_id_13 FROM article a0_ WHERE (a0_.tag_values @> ?) = true ORDER BY a0_.date_published DESC LIMIT 50

The error:

An exception occurred while executing a query: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type json

DETAIL:  Token "Bogotá" is invalid.

CONTEXT:  JSON data, line 1: Bogotá

unnamed portal parameter $1 = '...

Do I need to cast the string I'm searching for? Or maybe CONTAINS is the wrong word, but should be a JSONB_ call?

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions