ajithlal's avatar

orWhere() condition in eloquent relationship

My users table has relations with user_pohots and user_profiles tables. I've to fetch data with these relations and I've to apply and orWhere condition to my user_profiles table. So I wrote the query like this:

     $users = User::with('photos')
            ->where(['role_id' => $roleId, 'status' => User::STATUS_APPROVED])
            ->whereHas('profile',function($q) use($roleId){
            return $q->orWhere('interested_in', '=', $roleId);
        })->paginate(6);

But it is orWhere condition is not working properly.

My relations are like this:

//user_profiles table
public function profile()
    {
        return $this->belongsTo(UserProfile::class, 'id', 'user_id');
    }

//user_photos table
 public function photos()
    {
        return $this->hasMany(UserPhoto::class, 'user_id', 'id');
    }
0 likes
5 replies
bobbybouwmann's avatar
Level 88

Normally you can't do this with a whereHas and you would need to use a join. However, I think you can use a orWhereHas here instead

   $users = User::with('photos')
    ->where(['role_id' => $roleId, 'status' => User::STATUS_APPROVED])
    ->whereHas('profile')
    ->orWhereHas('profile', function ($query) {
        $query->where('interested_in', '=', $roleId);
    })->paginate(6);

Looking at your query your orWhere is a bit weird. Because you can already do this with one whereHas right? Also if you first do a whereHas('profile') and then the orWhere it doesn't make sense at all.

What exactly are you trying to achieve here? When do you want the user to show up. When both where and whereHas match?

2 likes
ajithlal's avatar

@bobbybouwmann

//users table structure
id,role_id,status,...

//user_profiles table
id,user_id,interested_in,....

Example: I want to fetch all users having role_id 1(users table) or interested_in 1 (users_profile table.)

Please or to participate in this conversation.