我在 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/