Thursday, March 2, 2017

If statement in Laravel Eloquent

I have two Models which are joined through three id's to one 1 id. The model AdviceProtocol had three ids defined: threshold_category1_id, threshold_category2_id and threshold_category3_id. These are all three linked to id from the model Categories. The threshold_cateogry_id's can be a number linked to the categories.id, or null.

In my query, I need to go through three of the threshold_catogory_ids and if they are NOT NULL, retrieve the categories.name. The query that I have now:

$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories.name as Category_Name','categories.name as Category_Name2'])
            ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
            ->join('categories', function ($join)
            {
                $join->on('advice_protocols.threshold_category1_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category2_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category3_id', '=', 'categories.id');
            })

This query now returns the same category.name twice. I have tried to look up how other people have solved this problem, but i couldn't find something accurate online.




via Anna Jeanine

Advertisement