【发布时间】:2020-06-03 11:48:16
【问题描述】:
我正在尝试检索在 mysql 中保存为 json 的数据。我的迁移如下所示:
Schema::create('items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->json('add_ons')->nullable();
$table->timestamps();
});
我试过从邮递员那里保存下面的 JSON,它保存得很好。
{
"itemName": "chicken",
"addons": {
"required": false,
"min": 2,
"max": 3,
"data": [
{
"name": "sauces",
"type": [
{
"name": "white sauce",
"type": [
{
"name": "whiteOne",
"price": 10
},
{
"name": "whiteTwo",
"price": 20
}
]
},
{
"name": "red sauce",
"price": 10
}
]
}
]
}
}
现在,我尝试在 'white sauce' 下检索 'whiteOne' 的价格,除了 null 或 laravel 错误响应之外什么都没有。
我试过了
Item::whereJsonContains('add_ons->data->name','sauces')->get()
Item::whereJsonContains('add_ons->data->name','sauces')->find(16)
保存后'add_ons'列有以下数据:
{
"required": false,
"min": 2,
"max": 3,
"data": [
{
"name": "sauces",
"type": [
{
"name": "white sauce",
"type": [
{
"name": "whiteOne",
"price": 10
},
{
"name": "whiteTwo",
"price": 20
}
]
},
{
"name": "red sauce",
"price": 10
}
]
}
]
}
谁能帮帮我?
【问题讨论】:
-
我认为这是
add_ons->data的拼写错误 - 它必须是add_ons->addons->data -
感谢您纠正其中一个问题。尝试了你的建议,但它不起作用。@RobinGillitzer
-
你会得到什么:
Item::whereJsonContains('add_ons->itemName','chicken')->get(); -
Illuminate\Database\Eloquent\Collection {#306 ▼ #items: [] }@RobinGillitzer -
你的 MySQL 版本是多少?
标签: mysql json laravel laravel-6.2