vendredi 3 mai 2019

How to render data from a different table in hasMany relationship Laravel?

I have a table for users, candidate_skills and skills. A user has many candidate_skills. Each candidate_skill belongs to a user and also belongs to a skill.

The candidate_skills table has these columns:

id
user_id 
skill_id
years_xp
comfort_level
created_at
updated_at

The skills table has an

id
name
...

Each user can pick a skill from from the skills table. That record gets added as a candidate_skill.

I am rendering a list of users and I'd like to render the skills that each candidate has. On my user model I have a method to grab a user's candidate_skills:

public function skills()
{
   return $this->hasMany('App\CandidateSkill');
}

How do I populate this list with the names of the skills from the skills table?

Right now I'm grabbing the results like:

$candidates = User::whereIn('department_id', $departmentFilters)
            ->whereIn('work_authorization', $workAuthFilters)
            ->orderBy('updated_at', 'desc')
            ->with('skills')
            ->get();

return response()->json($candidates);

This loads the list of candidate_skills but doesn't include a readable name for what the skill is. The result of the above query gives $candidate->skill like:

{ "id": 22, "user_id": 43, "skill_id": 64, "years_xp": 2, "comfort_level": null, "created_at": "2019-04-15 18:51:14", "updated_at": "2019-04-15 18:51:14" }

How can I include the name of the skill when rendering the candidate_skills for a user?

For example, skill with id of 64 has a name "PHP". When displaying user 43 I'd like to list out their skill with the name "PHP" instead of 64.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2VDRknZ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire