Laravel 5.2查询1个表的邮政编码,然后获取ID并查询另一个


Laravel 5.2 query 1 table for postcode then grab ids and query another

我正在努力学习如何进行查询。搜索字段用于存储在用户_文件(并且用户_文件与用户有关系)内部的邮政编码

所以我有一些返回一个结果的东西(然而有不止一个),但我听说为一个做两个查询是糟糕的

public function index()
{
    $queryUsername = Request::get('username');
    $queryPostcode = Request::get('postcode');
    if ($queryUsername) {
        $users = User::where('username', 'LIKE', "%$queryUsername%")->get();
    }
    if ($queryPostcode) {
        $usersInfo = UserProfile::where('postcode', '=', "$queryPostcode")->value('user_id');
        $users = User::where('id', '=', "$usersInfo")->get();
    }
    return view('view', compact('users'));
}

对于引用的问题,更好的方法是使用联接,而不是两个不同的查询

public function index()
{
    $queryUsername = Request::get('username');
    $queryPostcode = Request::get('postcode');
    if ($queryUsername) {
        $users = User::where('username', 'LIKE', "%$queryUsername%")->get();
    }
    if ($queryPostcode) {
        $users = Users::rightJoin('user_profiles','users.id', '=', 'user_profiles.user_id')
            ->where('user_profiles.postcode', '=', "$queryPostcode")
            ->select('DB::raw('users.*'))
            ->get();
    }
    return view('view', compact('users'));
}

如果你正在寻找一个完全匹配的用户名使用LIKE进行用户名匹配是不好的$users=用户::其中('username','LIKE',"%$queryUsername%")->get();因为对于用户名chris和chrisgeorge和christy,查询%chris%将起作用,并且您不会得到完全匹配,所以建议使用"=",而不是像一样

试试这个:

public function index(){
    $queryUsername = Request::get('username');
    $queryPostcode = Request::get('postcode');
    if ($queryUsername):
        $users = User::where('username', 'LIKE', "%".$queryUsername."%")->get();
    elseif ($queryPostcode):
        $usersInfo = UserProfile::where('postcode', '=', $queryPostcode)->value('user_id');
        $users = User::where('id', '=', "$usersInfo")->get();
    endif;
    return view('view', compact('users'));
}