Tuesday, March 21, 2017

Merge to column's values with same name

Using Lumen, I have two different tables [resources and platforms] and a table called resource_platform with two foreign keys [resource_id and platform_id], each platform can have from one to five platforms, so I need to do a query in order to obtain all the resource data and on the platforms field the value from as many platforms as the resource has.

This has to be done through a query build since I can't create another model to do a hasMany relationship.

If I use

Return $this->model->select(
  'resources.*',
  'platforms.name as platform'
)
->join('resources_platforms', 'resources.id', '=', 'resources_platforms.resource_id' )
->join('platforms', 'resources_platforms.platform_id', '=', 'platforms.id' )
->where('resources.id', $id)->get();

I get a JSON in which every resource is repeated but with a different platform value each time. and if I add ->pluck('platform') instead of get() at the end of the query I obtain ["Mac","Windows"] which is what I need but with all the remaining info for the resource.



via Miguel López

Advertisement