Skip to content

Instantly share code, notes, and snippets.

@sorokadima
Last active May 20, 2020 09:12
Show Gist options
  • Save sorokadima/6c42c4b595009592f5c38379a617ccc1 to your computer and use it in GitHub Desktop.
Save sorokadima/6c42c4b595009592f5c38379a617ccc1 to your computer and use it in GitHub Desktop.
JSON mysql - find in mysql by json field (sql, json, JSON_EXTRACT, order, select, yii2, yii)

select

select * from cars WHERE JSON_EXTRACT(data, "$.color") = 'red';

order

select * from cars ORDER BY JSON_EXTRACT(data, "$.color") DESC;

tuning_color - GridView column class

info - table name

data - JSON column name

color - parameter to sort

Example

info.data:

{"color":"red"}

Sort

$dataProvider->sort->attributes['tuning_color'] = [
    'asc' => ["JSON_EXTRACT(info.data, '$.color')" => SORT_ASC],
    'desc' => ["JSON_EXTRACT(info.data, '$.color')" => SORT_DESC],
];

Filter

->andFilterWhere([
  '=',
  "JSON_EXTRACT(info.data, '$.color')",
  (int) $this->tuning_color ?: $this->tuning_color
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment