Skip to content
Advertisement

Limiting retrieved columns when using withPivot on belonsToMany relationship

I have a model called Shifts with a belongsToMany relationship to a shift_employee table that acts as a pivot table to record applications for employees to shifts. I also have a scope so that I can return applications with shift objects. Here is part my Shift model:

JavaScript

My shift_employee pivot table is pretty simple and the structure is shown below. I have one extra field to determine if an application has been shortlisted:

JavaScript

Below is my API show function for retrieving shift info:

JavaScript

This is the response that I’m getting:

JavaScript

What I want to do, is to replace the whole “application” inner object with only the field “shortlisted” from the pivot table so that it looks like this:

JavaScript

How can I do that? Ideally an eloquent call to something like withPivot but that excludes other fields and does not return an object. I couldn’t find it in the docs, but does something like that exist?

Advertisement

Answer

i think that the most straightforward way is to make independent relation based on the pivot table using pivot model:

JavaScript

now the new relation in Shift Model:

JavaScript

now this new scope would bring the data you want

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement