Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Larvel:在mysql 5.7中,从JSON列获取单个列作为响应的查询_Php_Mysql_Json_Laravel - Fatal编程技术网

Php Larvel:在mysql 5.7中,从JSON列获取单个列作为响应的查询

Php Larvel:在mysql 5.7中,从JSON列获取单个列作为响应的查询,php,mysql,json,laravel,Php,Mysql,Json,Laravel,我有一个mysql数据库(5.7.1),表“inventory”包含两列: id{String} 内容{json} 内容列包含一个json,其中包含几个键: { "id" : "myId", "arrayOfEl" : [ {id : "1", always : true}, {id : "1", always : true} ] } 我尝试在laravel中进行查询,以便仅从指定id的内容列中获取arrayOfEl键: $in

我有一个mysql数据库(5.7.1),表“inventory”包含两列:

  • id{String}
  • 内容{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
type列。您只需根据
->
符号对其进行过滤即可

->where('content->id', 'myId')

您可以使用
pull
仅获取所需的列

$inventory = Inventory::where('id', 'myId')->pluck('arrayOfEl');

是的,我的列具有json类型,因此我将使用'->'语法。但是我如何才能用这个方法只返回arrayOfEl键呢?就像一个普通的查询
->where('content->id','myId')->get(['arrayOfEl'])->get('arrayOfEl')
或者
Pull('arrayOfEl)
或者
->where('content->id',myId')->get(['arrayOfEl'])->map->get('arrayOfEl')
,就这些。