Skip to content
Advertisement

Laravel if statement in query

I am beginner php developer.

I have this code:

Model::selectRaw('clients.*, if((client_company_infos.name != "" , client_company_infos.type == 1),  client_company_infos.name, concat(client_infos.first_name, " ", client_infos.last_name)) as name')
            ->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
            ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
            ->get();

I have error:

“message”: “SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘== 1), client_company_infos.name, concat(client_infos.first_name, ” “, client_i’ at line 1 (SQL: select clients.*, if((client_company_infos.name != “” , client_company_infos.type == 1), client_company_infos.name, concat(client_infos.first_name, ” “, client_infos.last_name)) as name from clients left join client_company_infos on client_company_infos.client_id = clients.id left join client_infos on client_infos.client_id = clients.id where clients.deleted_at is null)”,

When I make:

Model::selectRaw('clients.*, if(client_company_infos.name != "",  client_company_infos.name, concat(client_infos.first_name, " ", client_infos.last_name)) as name')
            ->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
            ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
            ->get();

It’s work fine. Problem. I with second if. How can I. repair it?

Please help me

Advertisement

Answer

There is no operator == in MySql.

You need to replace the condition with the following:

client_company_infos.type = 1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement