Dalma
4 months ago

I could use some assistance in formatting a query

Posted 4 months ago by Dalma

I have a query that I'm struggling to get to bracket correctly, query appears at the end of this post

I have three relations:

User
User->offices()
User->roles()

The User has a default office id stored in the office_id field and a ManytoMany relationship accessed via the User->offices() relation and ManytoMany relationship accessed via the User->roles() relation.

to pseudocode

if $myofficeid > 0 ( find user where office_id = $myofficeid OR user->offices().id = $myofficeid) AND user->roles() has name = "High Tech Coordinator)

what I'm getting now is effectively

if $myofficeid > 0  find user where office_id = $myofficeid OR (user->offices().id = $myofficeid and user->roles() has name = "High Tech Coordinator)

I assumed that trying to place both of the office related queries in the ->when closure would bracket them together.

$hightech = ['0' => 'Please Select'] + User::where('status','=',1)
            ->when($myofficeid > 0 , function($query) use($myofficeid){
                $query->whereHas('offices', function($query) use ($myofficeid){
                    $query->where('offices.id', '=', $myofficeid);
                })
                     ->orWhere('office_id','=',$myofficeid);
            })
            ->whereHas('roles', function ($query){
                   $query->where('name','=', 'High Tech Coordinator');
            })
            ->orderBy('name')->pluck('name','id')->toArray();

Please sign in or create an account to participate in this conversation.