Avatar of Eduardo Fuerte
Eduardo Fuerte
Flag for Brazil asked on

Could you point how to code an inline if for a select by using Laravel's Eloquent?

Hi Experts


Could you point how to code an inline if for a select by using Laravel's Eloquent?

Accordingly to

->select('users.id',...',
	// This generates an ERROR!	 
		 'if(users.aceiteRegulamento ==1, "Sim", "Não") as aceite','users.created_at','users.updated_at')

Open in new window


SQLSTATE[42S22]: Column not found: 1054 Unknown column 'if(users.aceiteRegulamento ==1, "Sim", "Não")' in 'field list' (SQL: select `users`.`id`, `users`.`login


Thanks in advance
LaravelPHP

Avatar of undefined
Last Comment
RBertora

8/22/2022 - Mon
RBertora

You need the Case statement (assuming you are asking about SQL Server SQL)

From https://stackoverflow.com/questions/6608102/sql-server-inline-if-else


select
 case MyFlag
   when 1 then 'YES'
   when 0 then 'NO'
   else 'OOPS'
 end
from MyTable
where it's used just like a switch in C-like languages and the other is:

select
 case
   when MyFlag = 1 then 'YES'
   when MyFlag = 0 then 'NO'
   -- when some unrelated condition...
   else 'OOPS'
 end
from MyTable
Eduardo Fuerte

ASKER
Hi

I'm using Laravel Eloquent and had attempt  to use it, also:

'(CASE WHEN users.aceiteRegulamento = "0" THEN "Não" WHEN users.aceiteRegulamento = "1" THEN "Sim" ELSE "Não" END) AS aceiteRegulamento'

Open in new window


But it doesn't run inside the query.
ASKER CERTIFIED SOLUTION
RBertora

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Eduardo Fuerte

ASKER
Rbertora

Perfectly!!!

Thank you for the help!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
RBertora

Hey Eduardo, thank you very much, muchas gracias / Muito obrigado for the positive review!