doufei9946 2019-08-06 08:12
浏览 239
已采纳

如何在类似搜索中使用ORM从两个表中获取数据 - 使用Laravel

This is my Controller code:

         public function searchUser(Request $request)
{
    $pram = $request->name;

    $data['users'] = User::whereHas('userBasicInfo', function ($query) use ($pram) {
        $query->where('first_name', 'like', '%' . $pram . '%')
            ->orWhere('middle_name', 'like', '%' . $pram . '%')
            ->orWhere('last_name', 'like', '%' . $pram . '%');
    })->with(['userBasicInfo' => function ($query) use ($pram) {
        $query->where('first_name', 'like', '%' . $pram . '%')
            ->orWhere('middle_name', 'like', '%' . $pram . '%')
            ->orWhere('last_name', 'like', '%' . $pram . '%');
    }])->get();

    return $data;
}

I have relationship of user with userBasicInfo i can search with first_name, middle_name and last_name and my request parameter is name

Now i want to search with user email and there will be one more request parameter which is email and email is in users table

How i can search with user email as well i am confused here anyone please help me

Your help will be highly appreciated!

  • 写回答

1条回答 默认 最新

  • dongxun1142 2019-08-06 08:55
    关注

    Try like

    $data['users'] = User::with('userBasicInfo')
                ->where('email', 'like', '%' . $pram . '%') //this is from use table
                ->orWhereHas('userBasicInfo', function($query) use($pram) {
                    //search in basic info table
                    $query->where('first_name', 'like', '%' . $pram . '%')
                        ->orWhere('middle_name', 'like', '%' . $pram . '%')
                        ->orWhere('last_name', 'like', '%' . $pram . '%');
                })
                ->get();
    

    You don't need to send different value from the search form. A single value can be used as the search value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?