mercredi 22 août 2018

Laravel hasManyThrough and grouping data with eloquent

I have a problem with hasManyThrough in laravel eloquent, it is possible that my model will not handle this functionality?

Database model

Based on the model above, I would like to retrive category_name from CategorySkill for each StudentObservationDetail using for this hasManyThrough realtion and table Skill.

Basically what I want to achieve is some kind of out of box grouping for my array, straight in Eloquent, without doing any loops.

For example: If my skill table has following data:

id: 1
category_id: 5
skill_name: running

There's eager loading that would allow me to access this data with -> operator like

$skill = Skill::with('category')

Then I could do:

$skill->category->name, but it's nested inside after I do toArray().

I would like my array to kind of replace category_id in Skill into category_name directly. So after doing $skill->toArray() I would have this:

array(
{
id: 1
category_id: 5
name: running
category_name: 'Motor Skills'
});

With simple select, I would get a row like this by doing proper joins and following select:

SELECT skill.id, skill.category_id, skill.name, category.name AS 'category_name'



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire