简体   繁体   中英

How to fetch polymorphic relation matching data?

I have three tables Jobseekers, Preferences and Industries. Preferences table is foreign table of Jobseeker and Preferences is connected with Industries table with polymorphic relation. Table structure as below:

jobseekers
id:
name:
email:
Phone:

preference
id:
job_title:
Location:
Salary:
jobseeker_id:

industryables
industry_id: 2
industryable_id: 1
industryable_type: App\Models\Preference

I am now able to store and fetch all data using this technique, but how can I fetch specific data based on industry. For example, if I want to fetch those jobseekers only who match certain Industry id, or I want to pass industry id on query and fetch matching jobseekers and show their profiles only. Is it possible or not, please somebody help me.

$jobseekers = Jobseeker::with(['preference.industries' => function($query) {
        $query->where('industry_id', '=', 7);
    }])->get();

Above code fetching all jobseekers with empty industries array and jobseekers with industry id 7 have industries values. My goal is to fetch only those jobseekers who have industry id 7 or something like that.

Its a total guess, because

  1. You haven't shared the schema of the table so I am guessing how they are linked.
  2. You haven't put them in a codepen, so I can't test the query
  3. I am unfamiliar with laravel so I can only give you the mysql query.
select j.*, p.*, i.*  // select the fields you actually want
from jobseekers j
inner join industryables i on i.industryable_id = j.id
left outer join preference p on p.jobseeker_id = j.id
where i.industry_id = 7

The inner join ensures that you only get the records that exist on both tables (jobseekers and industryables)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM