Hello,
I try to do to a conditinal query with laravel but I don't know how do something like a switch or multiple if.
I read the documentation with "when" but I don't really think it's the good way.
This is an example of what I try to do (replace if else if by ????)
$user = DB::table('address as a')
->select(DB::raw('CASE
WHEN a.type == 'A' THEN something_1
WHEN a.type == 'B' THEN something_2
ELSE default END'))```
How can I do to add by exemple with('relationship_A') inside map ?
#somnathsah, thank you but I can't use your solution on a sql query ->select(DB::raw because in my condition, I need to add eager loading relationship who are not of the same database (mysql and oracle), so I need use functions in models.
In that case you can't really use with() because with gets used during the execution of the query. You would have to use each() instead of map() and then use load() instead of with(). But that would actually remove all the purpose of eager loading because you would execute another query for every user which is exactly the problem eager loading tries to avoid.
if ($user->address->type == 'A') {
$user->load('relationship_A');
}
it's ok with User::with('address')->first () but not with User::with('address')->get() which is a collection.
I always need to execute query for every user if I have a collection.
The example of official laravel website on Eager Loading is with an external condition, I think it's more difficult in my situation where the condition come from my query.
#Snapey. Polymorphic relationship is a good idea but In my projet, one of my table I need is from an proprietary external software database (I can't add or modify column), so I can't add xxxxxx_id and xxxxxx_type columns.