我想返回给定用户的约会列表(约会表包含 user_id 和 post_id)。
问题是,返回的集合只得到了第一次约会的名字和地点。
public function index()
{
// Retrieve all appointments from the user
$appointments = Appointment::where('user_id', Auth::user()->id)->get();
// Retrieve all post IDs associated with the appointments
$postIds = $appointments->pluck('post_id')->toArray();
// Retrieve all posts with the associated post IDs
$posts = Post::whereIn('id', $postIds)->get()->keyBy('id');
// Assign post details to each appointment
$appointments = $appointments->map(function ($appointment) use ($posts) {
$postId = $appointment->post_id;
if (isset($posts[$postId])) {
$post = $posts[$postId];
$appointment->name = $post->name;
$appointment->place = $post->place;
} else {
// For debugging purposes, log the missing post details
Log::info("Post details not found for appointment: " . $appointment->id);
}
return $appointment;
});
return $appointments;
}
我在邮递员中得到的结果如下:
[
{
"id": 4,
"user_id": 9,
"post_id": 2,
"date": "6/14/2023",
"day": "Wednesday",
"time": "12:00 PM",
"status": "upcoming",
"created_at": "2023-06-12T17:19:58.000000Z",
"updated_at": "2023-06-12T17:19:58.000000Z",
"name": "Biskra",
"place": "Tolga"
},
{
"id": 5,
"user_id": 9,
"post_id": 9,
"date": "6/24/2023",
"day": "Saturday",
"time": "14:00 PM",
"status": "cancel",
"created_at": "2023-06-12T18:53:45.000000Z",
"updated_at": "2023-06-12T18:53:45.000000Z"
},
{
"id": 6,
"user_id": 9,
"post_id": 8,
"date": "6/17/2023",
"day": "Saturday",
"time": "12:00 PM",
"status": "complete",
"created_at": "2023-06-13T01:43:14.000000Z",
"updated_at": "2023-06-13T01:43:14.000000Z"
}
]
我想获取用户的约会列表以及每个约会的信息(日期,时间,日期,post_name,post_place)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题在于尝试修改原始约会以获得结果,请检查您的代码
// Assign post details to each appointment $appointments = $appointments->map(function ($appointment) use ($posts) { }结果必须放置在不同的变量中才能得到正确的结果
// Assign post details to each appointment $allTheRecords = $appointments->map(function ($appointment) use ($posts) { $postId = $appointment->post_id; if (isset($posts[$postId])) { $post = $posts[$postId]; $appointment->name = $post->name; $appointment->place = $post->place; } else { // For debugging purposes, log the missing post details Log::info("Post details not found for appointment: " . $appointment->id); } return $appointment; }); return $allTheRecords;