如何在Laravel中编写MySQL查询:根据登录用户ID获取关联BlindDate与PaidDate表的目标数据
Laravel 关联查询实现指定格式数据输出
嘿,我来帮你搞定这个Laravel的查询需求!根据你想要的输出格式,我们可以通过Eloquent关联和集合操作轻松实现,下面是具体的代码和步骤:
1. 先定义模型关联
首先需要在BlindDate和PaidDate模型中定义与User模型的关联关系,这样我们就能方便地关联查询对方用户的信息:
BlindDate 模型关联
// app/Models/BlindDate.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class BlindDate extends Model { // 假设你的BlindDate表中用touser_id存储对方用户ID,可根据实际字段名调整 public function touser() { return $this->belongsTo(User::class, 'touser_id'); } }
PaidDate 模型关联
// app/Models/PaidDate.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class PaidDate extends Model { // 同样根据实际字段名调整外键 public function touser() { return $this->belongsTo(User::class, 'touser_id'); } }
2. 查询并格式化数据
接下来在控制器或者业务逻辑层中,我们可以查询指定用户ID(这里是109)的相关记录,关联获取对方用户信息,再格式化成你需要的结构:
// 获取当前登录用户ID,实际项目中推荐用auth()->id(),这里直接用给定的109示例 $userId = 109; // 查询并格式化BlindDate相关数据 $blindUsers = BlindDate::where('user_id', $userId) ->with('touser:id,name,email') // 只加载需要的字段,避免冗余查询 ->get() ->map(function ($dateRecord) { return [ 'uuid' => $dateRecord->uuid, 'user_id' => $dateRecord->user_id, 'touser' => [ [ 'name' => $dateRecord->touser->name, 'email' => $dateRecord->touser->email ] ] ]; }); // 查询并格式化PaidDate相关数据 $paidDateUsers = PaidDate::where('user_id', $userId) ->with('touser:id,name,email') ->get() ->map(function ($dateRecord) { return [ 'uuid' => $dateRecord->uuid, 'user_id' => $dateRecord->user_id, 'touser' => [ [ 'name' => $dateRecord->touser->name, 'email' => $dateRecord->touser->email ] ] ]; }); // 组装成目标格式的数组 $data = [ 'blind_users' => $blindUsers->toArray(), 'paid_date_users' => $paidDateUsers->toArray() ]; // 如果需要返回JSON响应,直接使用下面的代码 // return response()->json($data);
注意事项
- 如果你的
BlindDate和PaidDate表中存储对方用户ID的字段不是touser_id,一定要修改模型关联方法中的外键参数。 - 使用
with('touser:id,name,email')可以有效避免N+1查询问题,同时只获取我们需要的字段,提升查询性能。 map方法的作用是将Eloquent集合转换为你需要的自定义数组结构,确保输出格式完全匹配要求。
内容的提问来源于stack exchange,提问作者kirtan
相关产品推荐
相关产品推荐

