Skip to content
Advertisement

Laravel Eloquent query siblings in same table with eager loading

I have a parent table called patients which has a one-to-many relationship with a child table called notes. (i.e. One patient can have several notes). If given a note, I would like to find other notes for the same patient. Notes are related to patients by a fk called patient_id.

In SQL, I’d do this:

SELECT * FROM notes WHERE patient_id={note.patient_id} AND id <> {note.id}

In Eloquent, I have this:

JavaScript

In my database, the patient with id=1 has two notes with ids 1 and 2, so if I look for the siblings of note id 1, I should get note id 2.

When I use find(), it works as expected, but when I use where(), it returns the original note instead of the sibling. Any ideas?

JavaScript

Advertisement

Answer

Given a Note id, you could obtain the results you want by using the relationship with the Patient model.

JavaScript

Or using a subquery

JavaScript

The later, you could turn into a query scope

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