'mysql ORDER BY depending on column

I have the table client_contacts like:

id client_id contact_type_id data
1 1 3 [email protected]
2 2 4 +999 999 999
3 .. .. ....

In my contact_types table I have the following types:

id description
1 address
2 fixed phone
3 email
4 mobile

I want the ability to sort all the contacts that are in the data column and by that, the possibility to sort with the contact_type_id. How to do it in Laravel 8 with Eloquent\Builder? I am using paginate as well.

Some uses: Sort ASC all the emails and furthermore the possibility to sort two contact_types like fixed phone ASC and mobile DESC.

In my client model, I have hasMany() to the client_contacts model.



Solution 1:[1]

According to documentation:

MYSQL: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_field

LARAVEL: https://laravel.com/docs/9.x/queries#orderbyraw

You can Add This Quote Of Code:

->orderByRaw("FIELD(contact_types.description, 'addresses', 'fixed phones', 'email', 'mobile') ASC")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hicham AIT TALGHALIT