我有一个名为候选人表的表,其中包含以下列:
'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个表,我不会遇到这个问题,但是我要从多个表中获取数据。
如何以这种方式为每个候选人资料记录获取正确的数据?
答案 0 :(得分:0)
您可以在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