I tried something like this. All predefined standard colors would get translated, user defined ones in the language what they used during naming.
Then I could use translated_name as search and order column and everything would work like expected. Unfortunatelly, when I add this function, my closure function does not find the translated_name column.
PHP Code:
/**
* Get localized color names
*
* @return object result with additional localized name column
*/
public function withLocalizedNames() {
$this->builder()->select('
CASE
WHEN name = "Colors.black" THEN "' . lang('Colors.black') . '"
WHEN name = "Colors.blue" THEN "' . lang('Colors.blue') . '"
WHEN name = "Colors.green" THEN "' . lang('Colors.green') . '"
ELSE name
END AS translated_name', false);
return $this;
}
PHP Code:
$data['colors'] = $this->model
->select()
->withLocalizedNames()
->when($data['search'] !== '', function ($query) use ($data) {
return $query
->like('color', $data['search'], 'both')
->orLike('color2', $data['search'], 'both')
->orLike('translated_name', $data['search'], 'both');
})
->orderBy($data['sortColumn'], $data['sortDirection']);
Edit:
Well, the solution above works pretty good for correct order, since I can order by column translated_name. The problem I am facing now is the logical SQL execution order.
WHERE is executed before SELECT, thus the column translated_name does not exist when WHERE is compared.
Any SQL gurus around that can rewrite this query? Runtime add a column with translated values that I can compare in WHERE clause?
Code:
SELECT *, CASE
-> WHEN name = "Colors.black" THEN "schwarz"
-> WHEN name = "Colors.blue" THEN "blau"
-> WHEN name = "Colors.green" THEN "grün"
-> ELSE name END AS translated_name FROM `colors` WHERE `translated_name` LIKE '%schwarz%';