我有一个 mysql 数据库(5.7.1),其中有一个包含 2 列的“inventory”表:
- id {字符串}
- 内容 {json}
内容列包含一个带有多个键的 json:
{
"id" : "myId",
"arrayOfEl" : [
{id : "1", always : true},
{id : "1", always : true}
]
}
我尝试在 laravel 中进行查询,以从指定 id 的内容列中仅获取 arrayOfEl 键:
$inventory = Inventory::where('id', "myId")->get(????);
如何不知道在查询中指定的位置仅获取响应中的子列 arrayOfEl ?
最佳答案
除非您的表是 json
类型,否则您可能需要获取整行,然后尝试过滤它们。确保在模型上定义属性转换,此处使用集合的示例
protected $casts = [
'arrayOfEl' => 'collection',
];
然后尝试寻找匹配
$myId = 'myId'; // id of content
$inventory = Inventory::all()->filter(function ($item) use ($myId) {
return is_object($item->content) && $item->content->id == $myId;
})->first();
或者如果您有 json
类型列。您可以简单地根据 ->
表示法对其进行过滤。
->where('content->id', 'myId')
关于php - 拉拉维尔 : Query to get a single column in response from a JSON column in mysql 5. 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084004/