Skip to content
Advertisement

Laravel 5.5 BelongsToMany with pivot conditions

I have three models, Clinic, Department and ClinicDepartment and has belongsToMany relation called departments from Clinic to Department using ClinicDepartment‘s table as pivot table, but when i using this relation, scopes from ClinicDepartment not aplying in query.

I decided to make Pivot model calling ClinicDepartmentPivotand apply those scopes to Pivot, but no luck.

Clinic model:

JavaScript

Department Model:

JavaScript

ClinicDepartmentPivot Model:

JavaScript

ActiveOnlyScope:

JavaScript

So basicaly I want to apply global scopes to Pivot model, so when I trying to get Clinics of Department, it should check – is ClinicDepartment has is_active = 1 and not deleted.

UPD 1

My scope traits looks like this:

JavaScript

Can be used by any model.

Advertisement

Answer

Okay, with some workaround I finally found a working solution that does not look scrappy.

JavaScript

Actual query looks like this:

JavaScript

Thanks all for the ideas.

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