简体   繁体   中英

Laravel : Query to get a single column in response from a JSON column in mysql 5.7

I have a mysql database (5.7.1) with a table "inventory" containing 2 columns :

  • id {String}
  • content {json}

The content column contains a json with severals keys:

{
     "id" : "myId",
     "arrayOfEl" : [
        {id : "1", always : true},
        {id : "1", always : true}
     ]
}

I try to make a query in laravel to get only the arrayOfEl keys from the content column of the specified id:

$inventory = Inventory::where('id', "myId")->get(????);

How don't know where specify in the query to get only the sub-column arrayOfEl in response ?

Unless your table is json type, you might need to fetch the whole rows then try to filter them. Make sure you define attribute casting on the model, example here using collection

protected $casts = [
    'arrayOfEl' => 'collection',
];

And then try to find match

$myId = 'myId'; // id of content
$inventory = Inventory::all()->filter(function ($item) use ($myId) {
   return is_object($item->content) && $item->content->id == $myId;
})->first();

Or if you have json type column. You can simply filter it based on -> notation.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM