简体   繁体   中英

Laravel whereHas() not filtering by where clause correctly

I'm attempting to search players by name and their parents by name/email address. For some reason the below statement is pulling all players regardless of the search term I enter.

In the below example "guardian" references the users table.

    $players = Player::where('first_name', 'LIKE', '%'.Input::get('q').'%')
        ->orWhere('last_name', 'LIKE', '%'.Input::get('q').'%')
        ->orWhereHas('guardian', function ($q) {
            $q->where('users.first_name', 'LIKE', '%'.Input::get('q').'%')
                ->orWhere('users.last_name', 'LIKE', '%'.Input::get('q').'%')
                ->orWhere('email', 'LIKE', '%'.Input::get('q').'%');
        })
        ->with('guardian')
        ->orderBy('last_name', 'ASC')
        ->orderBy('first_name', 'ASC')
        ->paginate(25);

Maybe it's just been a long day... but I think I'm missing something.

Example: 在此处输入图片说明

I think you should call with() method before your wheres statements. Maybe something like this:

     $players = Player::with('guardian')
                ->where('first_name', 'LIKE', '%'.Input::get('q').'%')
                ->orWhere('last_name', 'LIKE', '%'.Input::get('q').'%')
                ->orWhereHas('guardian', function ($q) {
                    $q->where('users.first_name', 'LIKE', '%'.Input::get('q').'%')
                        ->orWhere('users.last_name', 'LIKE', '%'.Input::get('q').'%')
                        ->orWhere('email', 'LIKE', '%'.Input::get('q').'%');
                })
                ->orderBy('last_name', 'ASC')
                ->orderBy('first_name', 'ASC')
                ->paginate(25);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM