我有2个表:User和User_login_log
我在 Laravel 中编写了一条 select 语句来获取特定用户的数据,并希望从 User_login_log 中检索他们的登录月份。
但是,问题是我在 User_login_log 表中为单个用户有多个条目。 喜欢:
User Id Month_no
2022 2
2022 3
2022 4
如果我将 User_login_log 表与 User 表右连接,并写入:
$result = User::rightjoin('user_login_logs', 'user_login_logs.user_id', 'users.id')
->select(;users.id', 'users.first_name', 'users.last_name','user_login_logs.month_no')
->where( 'users.batch_id', session()->get('batch_id'))
->whereIn('users.id', $array)...
然后我在检索到的数据中只得到 1month_no。
got result:
User_id first_name last_name Month_no
2022 **** **** 2
2023 **** **** 1
我想要结果:
User_id first_name last_name Month_no
2022 **** **** 2,3,4
2023 **** **** (login months)
我认为你应该使用 left 连接以及原始选择和
GROUP_CONCAT()
:
$result = User::leftjoin('user_login_logs', 'user_login_logs.user_id', 'users.id')
->selectRaw('users.id, users.first_name, users.last_name, GROUP_CONCAT(user_login_logs.month_no ORDER BY user_login_logs.month_no) AS Month_no')
->where('users.batch_id', session()->get('batch_id'))
->whereIn('users.id', $array);