我想返回给定用户的约会列表(约会表包含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;
}
我在Postman中得到的结果如下:
[
{
"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"
}
]
我想得到的每个约会(日期,时间,天,职位名称,职位地点)的信息用户的约会列表
2条答案
按热度按时间0tdrvxhp1#
问题是试图修改原始约会以获得结果,请检查您的代码
结果必须放在不同的变量中才能得到正确的结果
bbmckpt72#
如果您正在构建一个API来根据需要转换数据,则可以使用Eloquent: API Resources。
将索引函数更改为eager load
post
with appointments并返回一个资源集合。如果您的约会模型还没有
post
关系,请添加它。使用以下命令创建新资源
在您的
App\Http\Resources\AppointmentResource
;如果你不需要转换数据,只需要访问数据,你可以在像
$appoinment->post->name
这样的视图中迭代时访问post
关系。