我無法讀取所有數​​據表,它只返回正確的第一行
P粉645569197
P粉645569197 2023-09-12 15:48:04
0
1
581

我想傳回給定使用者的約會清單(約會表包含 user_idpost_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)

P粉645569197
P粉645569197

全部回覆(1)
P粉718730956

問題在於嘗試修改原始約會以獲得結果,請檢查您的程式碼

// 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;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!