php - 在 MySQL JSON 字段的数组中搜索值 (Laravel/Lumen)

标签 php mysql json lumen laravel-query-builder

我在 MySQL JSON 字段内的数组(图像路径)中搜索值时遇到问题。我想检查数据库中是否存储了图像的路径以防止删除文件。

我尝试过的 Controller 功能:

public function checkImage($filename){
    $content = Content::whereRaw('JSON_CONTAINS(images->"$.path", lAeH88gIv4HeycQXHeMbT8yOyydybbOVhsSq9eAx.jpeg')->exists();
    $content = Content::whereRaw('json_contains(images->path, \'["lAeH88gIv4HeycQXHeMbT8yOyydybbOVhsSq9eAx.jpeg"]\')')->exists();
    $content = Content::whereRaw('json_contains(images->path, \'["' . $filename . '"]\')')->exists();
    $content = Content::whereRaw('json_contains(images, \'["' . $filename . '"]\')')->exists();
    return response()->json($content);
}

示例 JSON:

{
    "id": 4,
    "images": [
        {
            "path": "abc/abc123.jpg",
            "caption": "text",
            "credits": "text"
        },
        {
            "path": "abc/xyz123.jpg",
            "caption": "text",
            "credits": "text"
        },
        {
            "path": "abc/827364527.jpg",
            "caption": "text",
            "credits": "text"
        }
    ],
    "created_at": "2017-12-20 11:40:16",
    "updated_at": "2018-01-04 12:46:37"
}

最佳答案

我已经找到解决办法了。下面是我的 Controller 功能:

public function checkIfImageExists(){
$content = Content::where('images', 'like',  '%image-name-123.jpg%')->exists();
return response()->json($content);
}

如果图像用于数据库 JSON 字段,则函数返回 true。如果未使用则为 False。

关于php - 在 MySQL JSON 字段的数组中搜索值 (Laravel/Lumen),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794410/

相关文章:

php - laravel 5 Controller 中的 CSV 导出

php - 前 30 天到期后,如何取消每月定期费用?

php - 使用php将大量mysql记录转换为json

java - 为什么对于 POST 请求,Retrofit2 使用 @Field 而不是 @Body

java - 获取XML数据后,如何解析它并转换为JSON?

php - 使用下拉菜单编辑 mysql 数据

php - 删除/隐藏具有 'Pass' 结果的类似记录

java - 需要帮助了解 mySQL、POJO、hibernate 和 JSP

MySQL服务器经常关闭

php - Json返回字符