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

如何在类似搜索中使用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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题