从数据库条目的 JSON 字段中使用 Eloquent 搜索特定键的值

huangapple go评论57阅读模式
英文:

Search specific key's value from a json field database entry using eloquent

问题

以下是翻译好的部分:

你好大家,请帮忙,我正在处理一个系统,需要添加一个查询,接收存储在变量 $search 中的搜索词,并从数据库中提取特定键的 JSON 字段中所有匹配的值。

我已尝试以下代码:

$query = Book::whereJsonContains('book_details->author', ['like' => "%{$search}%"])->get();

Book 是我的模型,book_details 是 JSON 字段的名称,author 是键。我想检索与搜索词相关的每本书的作者。

英文:

Hello everyone please I am working on a system and need to add a query that receives a search term stored with the variable $search and fetch all matching values for a specific key in a json field from database.

I have tried the code bellow

$query = Book::whereJsonContains('book_details->author',['like'=>"%{$search}%"])->get();

Book is my model, book_details is the json field name and author is the key. I want to retrieve every book with authors related to the search term

答案1

得分: 0

在Laravel中,您可以使用whereJsonContains方法执行查询,以检索特定键的JSON字段中的所有匹配值。您的代码的修订版本可能如下所示:

$query = Book::whereJsonContains('book_details->author', $search)->get();

此查询将返回所有Book记录,其中book_details JSON字段中的author键的值包含存储在$search变量中的搜索词。

请注意,您不需要在搜索词周围包装%字符,因为whereJsonContains方法默认执行不区分大小写的匹配值搜索。

英文:

In Laravel, you can perform a query that retrieves all matching values for a specific key in a JSON field by utilizing the whereJsonContains method. A revised version of your code could look like this:

$query = Book::whereJsonContains('book_details->author', $search)->get();

This query will return all Book records where the value of the author key in the book_details JSON field contains the search term stored in the $search variable.

Note that you don't need to wrap the search term in % characters, as the whereJsonContains method performs a case-insensitive search for matching values by default.

huangapple
  • 本文由 发表于 2023年2月8日 17:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定