gpt4 book ai didi

mysql - 如何使用原始 Laravel 在 json_contains 中设置变量?

转载 作者:行者123 更新时间:2023-11-29 15:59:30 26 4
gpt4 key购买 nike

通过使用 (1) 我从 laravel 请求中获得了想要的结果。但是,一旦我将硬编码的“fish”切换为 $str = 'fish' 这样的变量,就会出现语法错误。

(1) $find = animal::whereRaw('JSON_CONTAINS(animal_category, \'{"item_text": "fish"}\')')->get();

我已经在几乎任何地方使用 ' 或 ` 或 "尝试过各种变体,例如:

$find = animal::whereRaw("JSON_CONTAINS(animal_category, \'{'item_text': $str}\')")->get();

$str = 'fish'
$str2 = "\'{'item_text': $str}\'"
$find = animal::whereRaw("JSON_CONTAINS(animal_category, $str2)")->get();

但我正在尝试什么并不重要,总是语法错误或为空,因为请求正在寻找“$str2”。

我也尝试过不使用\{"item_text": "fish"} 。仍然存在语法错误...

我应该怎样做才能获得与硬编码示例相同的结果?

我的设置:Laravel 5.8,mysql 5.7.14

提前非常感谢您。 =)

其他信息 MySQL 列动物看起来像

[{"item_id": 1, "item_text": "fish"}, {"item_id": 6, "item_text": "birds"}]

也许还有另一种方法,然后是 json_contains,通过 where 子句获取数据? :)

最佳答案

您始终可以使用 jsonContains()方法:

$find = animal::whereJsonContains('animal_category', ['item_text' => $fish])->get();
<小时/>

要回答您的实际问题,为了获得您想要的东西,您可以执行以下操作:

whereRaw('JSON_CONTAINS(animal_category, \'{"item_text":"' . $fish . '"}\')')

whereRaw("JSON_CONTAINS(animal_category, '{\"item_text\":\"$fish\"}')")

但是,我强烈建议不要这样做,因为它会让您面临 SQL 注入(inject)(取决于您如何获取 $fish 变量)。

要解决这个问题,您可以像这样绑定(bind)值:

whereRaw('JSON_CONTAINS(animal_category, ?)', '{"item_text":"' . $fish . '"}')

关于mysql - 如何使用原始 Laravel 在 json_contains 中设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56295594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com