首页 > 解决方案 > 如何使用 Vue js 和 Laravel 加载基于 id 的数据?

问题描述

我有一个名为 Candidate_profiles 的表,其中包含以下列:

'user_id', 'photo_id', 'resume_id', 'video_one_id', 'video_two_id', 
'video_three_id', 'date_of_birth', 'employment_type', 'experience','skills'

我有一个页面/employer/search显示该表中的所有配置文件。我paginate用来每页显示 5 条记录。在底部我有一个“加载更多”按钮,单击时会出现另外 5 个(或更少)配置文件。如果还有,您仍然会看到“加载更多”按钮,否则它将消失。

这就是我获取数据的方式。

EmployerSearchController.php 文件:

public function search()
{
    $candidateProfile = CandidateProfile::orderBy('created_at', 'asc')->paginate(5);

    $user = User::all()->where('id', $candidateProfile->first()->user_id);

    $videoOne = Video::all()->where('id', $candidateProfile->first()->video_one_id);
    $videoTwo = Video::all()->where('id', $candidateProfile->first()->video_two_id);
    $videoThree = Video::all()->where('id', $candidateProfile->first()->video_three_id);
    $resumes = Resume::all()->where('id', $candidateProfile->first()->resume_id);
    $photos = Photo::all()->where('id', $candidateProfile->first()->photo_id);

    return response()->json(array($candidateProfile, $videoOne, $videoTwo, $videoThree, $resumes, $photos, $user), 200);

}

这就是我将数据分配给变量并在我的前端 Vue js 代码中创建加载更多功能的方式:

methods: {
        loadCandidateProfileData: async function() {
            try {
                const response = await employerService.loadCandidateProfileData();
                this.resumes = response.data[4];
                this.video_one = response.data[1];
                this.video_two = response.data[2];
                this.video_three = response.data[3];
                this.photos = response.data[5];
                this.users = response.data[6];

                this.candidateProfiles = response.data[0].data;

                if (response.data[0].current_page < response.data[0].last_page) {
                    this.moreExists = true;
                    this.nextPage = response.data[0].current_page + 1;
                } else {
                    this.moreExists = false;
                }

                // console.log(JSON.stringify(response.data, undefined, 4));

            } catch (error) {
                this.$toast.error("Some error occurred, please refresh!");
            }
        },

问题是因为我从他们各自的表中获取视频、简历和照片,我没有得到正确的信息,因为它没有查询正确的 id。

如果所有数据都来自 1 个表,我就不会有这个问题,但我从多个表中获取数据。

如何以这种方式为每个 Candidate_profile 记录获取正确的数据?

标签: laravelvue.js

解决方案


您可以在 CandidateProfile 模型上使用关系。请参阅此处https://laravel.com/docs/7.x/eloquent-relationships。因此,例如对于用户,您可以在 CandidateProfile 模型中使用

public function user()
{
    // You can choose the relationship that best suits your need for the users table
    return $this->belongsTo(User::class);
}

查询时,您可以通过

 $candidateProfile = CandidateProfile::with('users')->orderBy('created_at', 'asc')->paginate(5);

那么您可以通过以下方式访问这些用户

$candidateProfile->users

这同样适用于您的其他表格关系(视频、简历、照片)。

然后你可以直接传$candidateProfile回你的 vue js


推荐阅读