在 Laravel 框架中搜索 JSON 列。

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

Search in json column in framework laravel

问题

你想获取这个记录吗?

英文:

I have a column which contains

[
    {
        "type": "content",
        "data": {
            "content": "<p>\u043a\u0432\u0435\u0440\u0438\u0431\u0438\u043b\u0434\u0435\u0440<\/p>"
        }
    }
]

How can I get this record?

My code is:

$q = $request->get('q');

$posts = Post::query()
    ->where('active', '=', true)
    ->where('published_at', '<=', Carbon::now())
    ->latest('published_at')
    ->where(function($query) use ($q) {
        $query->whereJsonContains("content", [['type' => 'content', 'data' => ['content' => "%$q%"]]]);
    })
    ->paginate(10);

答案1

得分: 1

Sure, here are the translated parts:

1 将您的 JSON 字段添加到 cast

protected $casts = [
    'content' => 'array',
];

2 我使用俄语编码时,从数组编码为 JSON 时使用标志:

`$data['content'] = json_encode($data['block'], JSON_UNESCAPED_UNICODE);`

3 我的数据库查询如下:

`$posts = Post::query()->where("content", 'like',  "%$someValue%")->paginate(10);`
英文:

My solution:

1 Add your json field to cast

protected $casts = [
    'content' => 'array',
];

2 I work with russian language, when i encode to json from array i use flag:

`$data['content'] = json_encode($data['block'], JSON_UNESCAPED_UNICODE);`

3 My query in db looks like

`$posts = Post::query()->where("content", 'like',  "%$someValue%")->paginate(10);`

huangapple
  • 本文由 发表于 2023年5月25日 19:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331975.html
匿名

发表评论

匿名网友

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

确定