简体   繁体   English

Laravel whereHas() 没有正确过滤 where 子句

[英]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.在下面的示例中,“监护人”引用了users表。

    $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.我认为您应该在 wheres 语句之前调用 with() 方法。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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