Table of Contents
问题内容
解决方法
Home Backend Development Golang How to filter enum and include all rows if no filter value is provided

How to filter enum and include all rows if no filter value is provided

Feb 08, 2024 pm 10:30 PM

How to filter enum and include all rows if no filter value is provided

How to filter enum and include all rows if no filter value is provided?这是许多开发者在使用枚举类型时经常遇到的问题。在PHP中,我们可以使用array_filter函数来实现这个目标。array_filter函数可以将数组中的每个元素传递给一个回调函数进行过滤,并返回满足条件的元素所组成的新数组。回调函数可以使用in_array函数来判断元素是否存在于枚举中。通过这种方式,我们可以轻松地过滤枚举并包含所有行。

问题内容

我正在开发一个项目资源管理应用程序,我的资源表有多个字段,其中之一是一个枚举,如下所示:

create type "clearance" as enum (
  'none',
  'baseline',
  'nv1',
  'nv2',
  'tspv'
);
Copy after login

然后,我的资源表包含该枚举:

create table "resource" (
  "employee_id" integer primary key,
  "name" varchar not null,
  "email" varchar not null,
  "job_title_id" integer not null,
  "manager_id" integer not null,
  "workgroup_id" integer not null,
  "clearance_level" clearance,
  "specialties" text[],
  "certifications" text[],
  "active" boolean default 't'
);
Copy after login

查询数据时,我希望能够在网址中提供查询字符串参数,然后将过滤器应用于数据库查询。

例如(使用本地开发机器):

curl localhost:6543/v1/resources # returns all resources in a paginated query
curl localhost:6543/v1/resources?specialties=nsx  # returns all resources with nsx as a specialty
curl localhost:6543/v1/resources?manager=john+smith # returns resources that report to john smith
curl localhost:6543/v1/resources?jobtitle=senior+consultant # returns all senior consultants
Copy after login

等等

我遇到的问题是我还希望能够像这样过滤安全许可级别:

curl localhost:6543/v1/resources?clearance=nv2
Copy after login

当我提供间隙过滤器时,我可以让查询正常工作:

query := fmt.sprintf(`
        select count(*) over(), r.employee_id, r.name, r.email, job_title.title, m.name as manager, workgroup.workgroup_name, r.clearance_level, r.specialties, r.certifications, r.active
        from (((resource r
            inner join job_title on r.job_title_id=job_title.title_id)
            inner join resource m on r.manager_id=m.employee_id)
            inner join workgroup on workgroup.workgroup_id=r.workgroup_id)
        where (workgroup.workgroup_name = any($1) or $1 = '{}')
        and (r.clearance_level = $2::clearance)
        and (r.specialties @> $3 or $3 = '{}')
        and (r.certifications @> $4 or $4 = '{}')
        and (m.name = $5 or $5 = '')
        and (r.active = $6)
        and (r.name = $7 or $7 = '')
        order by %s %s, r.employee_id asc
        limit $8 offset $9`, clearance_filter, fmt.sprintf("r.%s", filters.sortcolumn()), filters.sortdirection())
Copy after login

但是,我无法找到一种合理的方法来实现过滤,以便在没有提供清除过滤器的情况下返回所有结果。

我让它工作的糟糕方法是,当没有过滤许可时,仅在另一个字段上应用空字符串过滤器,并在提供许可参数时替换为正确的过滤器。

它确实有效,但气味很难闻:

func (m *resourcemodel) getall(name string, workgroups []string, clearance string, specialties []string,
    certifications []string, manager string, active bool, filters filters) ([]*resource, metadata, error) {
    // this is a smell
    // needed to provide a blank filter parameter if all clearance levels should be returned.
    // have not found a good way to filter on enums to include all values when no filter argument is provided
    var clearance_filter = `and (r.name = $2 or $2 = '')`
    if clearance != "" {
        clearance_filter = `and (r.clearance_level = $2::clearance)`
    }

    query := fmt.sprintf(`
        select count(*) over(), r.employee_id, r.name, r.email, job_title.title, m.name as manager, workgroup.workgroup_name, r.clearance_level, r.specialties, r.certifications, r.active
        from (((resource r
            inner join job_title on r.job_title_id=job_title.title_id)
            inner join resource m on r.manager_id=m.employee_id)
            inner join workgroup on workgroup.workgroup_id=r.workgroup_id)
        where (workgroup.workgroup_name = any($1) or $1 = '{}')
        %s
        and (r.specialties @> $3 or $3 = '{}')
        and (r.certifications @> $4 or $4 = '{}')
        and (m.name = $5 or $5 = '')
        and (r.active = $6)
        and (r.name = $7 or $7 = '')
        order by %s %s, r.employee_id asc
        limit $8 offset $9`, clearance_filter, fmt.sprintf("r.%s", filters.sortcolumn()), filters.sortdirection())
...
...
}
Copy after login

有更好的方法来解决这个问题吗?

这感觉像是一个非常糟糕的解决方案,以至于我正在考虑删除枚举并使其成为另一个仅建立值域的表:

CREATE TABLE clearance (
 "level" varchar NOT NULL
);
Copy after login

解决方法

对于未来需要这个非常利基用例的任何人,答案是基于@mkopriva 的最初提示

该方法是将clearance_level转换为文本,因此过滤器是:

...
AND(r.clearance_level::text = $2 OR $2 = '')
...
Copy after login

当未提供间隙过滤器时,无论间隙如何,都会返回所有结果;当提供过滤器时,仅返回与所提供的间隙_级别匹配的结果。

非常感谢@mkopriva 的帮助。

The above is the detailed content of How to filter enum and include all rows if no filter value is provided. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

See all articles