Skip to content
Advertisement

How to get all the people in table 1 without getting the people who have me as parent_id in table 2?

I’m writing this post because I have a problem with my relationships on Laravel.

Here is the structure I currently have:

1st table: – id – name – …

2nd table : – parent_id – child_id

knowing that parent_id and child_id correspond to the same table. Here is the function that links them

JavaScript

Currently I would like, for a search system, to get all the people in table 1 without getting the people who have me as parent_id in table 2.

Advertisement

Answer

I have added an inverse relation parents() to the People model instead of the relation() method in the question.

Person Model :

JavaScript

Controller :

JavaScript

This method will return all records which doesn’t have a given $myId as their parent id.

Tested and working in Laravel 6.2 and 7.29

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