Sometimes when querying Espo you need to manage array or multi-enum fields.
If you use formulas, then https://docs.espocrm.com/administration/formula/array/ functions is your friend,
but if you need to, here are some SQL snippets that may help.
Example :
To manage these data, you may want to check if an item is available, add and item in the array or remove an item.
For this you can use the following functions
ADD AN ELEMENT TO ARRAY
CHECK IF AN ELEMENT EXISTS IN ARRAY
REMOVE AN ELEMENT FROM ARRAY
Example :
result
id.colors..............a..........b............... ................IsBlue
-------------------------------------------------------------------------
22.["yellow","blue"]...["blue"]...["yellow", "blue", "purple"]....1
If you use formulas, then https://docs.espocrm.com/administration/formula/array/ functions is your friend,
but if you need to, here are some SQL snippets that may help.
Example :
ID | Colors |
1 | NULL |
2 | ["yellow", "blue"] |
3 | ["yellow","green"] |
For this you can use the following functions
ADD AN ELEMENT TO ARRAY
Code:
CREATE FUNCTION `arrayAdd`(jsonField JSON, valueToAdd VARCHAR(255)) RETURNS json DETERMINISTIC BEGIN IF jsonField IS NULL THEN RETURN JSON_ARRAY(valueToAdd); ELSEIF JSON_CONTAINS(jsonField, JSON_QUOTE(valueToAdd)) THEN RETURN jsonField; ELSE RETURN JSON_ARRAY_APPEND(jsonField, '$', valueToAdd); END IF; END;
Code:
CREATE FUNCTION `arrayCheck`(jsonField JSON, valueToCheck VARCHAR(255)) RETURNS tinyint(1) DETERMINISTIC BEGIN IF jsonField IS NULL THEN RETURN FALSE; END IF; IF JSON_CONTAINS(jsonField, JSON_QUOTE(valueToCheck)) THEN RETURN TRUE; ELSE RETURN FALSE; END IF; END
Code:
CREATE FUNCTION `arrayRemove`(jsonField JSON, valueToRemove VARCHAR(255)) RETURNS json DETERMINISTIC BEGIN DECLARE jsonPath VARCHAR(255); IF jsonField IS NULL THEN RETURN NULL; END IF; SET jsonPath = JSON_UNQUOTE(JSON_SEARCH(jsonField, 'one', valueToRemove)); IF jsonPath IS NULL THEN RETURN jsonField; END IF; RETURN JSON_REMOVE(jsonField, jsonPath); END
Example :
Code:
select id, colors, arrayRemove(colors,"yellow") as a, arrayAdd(colors,"purple") as b, arrayCheck(colors,"blue") as IsBlue from (select 22 as id , '["yellow","blue"]' as colors ) t
id.colors..............a..........b............... ................IsBlue
-------------------------------------------------------------------------
22.["yellow","blue"]...["blue"]...["yellow", "blue", "purple"]....1
Comment