如何从数据透视表中检索元素

时间:2019-12-30 14:15:01

标签: laravel eloquent many-to-many relationship

我在job_seeker和job_offer之间有很多关系(数据透视表=“ job_seeker_job_offer) 我有一个页面,该页面显示特定雇主的所有工作机会,以及如何检索附加到特定job_offer上的job_seeker的人数

显示工作提供的功能

 public function show_jobs($id){
        // $categories=Category::all();
        $job_offer_all=Job_offer::all();
        $employer=Employer::find($id);
        $job_offers=Job_offer::where('employer_id',$employer_id)->with('employer')->get();
        return view('employer.my_jobs',compact('employer_id','employer','job_offers','n_applicant'));
       }

将求职者与求职者联系起来的功能

public function send_offer($id,$employer_id,$offer_id){
    $job_seeker=Job_seeker::find($id);
    $job_offer=Job_offer::find($offer_id);
    $employer=Employer::find($employer_id);
    // Notification::route('mail', $employer->email)
    // ->notify(new submit_job_demand($job_seeker));
    $job_seeker->job_offer()->attach($job_offer->id);

    }

1 个答案:

答案 0 :(得分:0)

假设您已经在两个方向上建立了关系,则可以使用withCount方法来计算关系:

$jobOffers = JobOffer::where('employer_id', $employer_id)
    ->withCount('job_seekers')
    ->with('employer')
    ->get();

foreach ($jobOffers as $offer) {
    echo $offer->job_seekers_count;
}

Laravel 6.x Docs - Eloquent - Relationships - Counting Related Models