Svyat Svyat - 10 months ago 42
MySQL Question

Can't retrieve records using foreign key on the same table in Laravel 5.2

I'm using Laravel 5.2 to retrieve records from a database.

My table (simplified):


parent_id is FK to the same table (FK to

This code returns an empty collection:

$category->services->where( 'parent_id', 0 )

Select with other where condition works properly. ex.

$category->services->where( 'name', 'foo )

returns not empty results.

Raw SQL works fine too:

SELECT * FROM services WHERE parent_id = 0;

What is wrong with Eloquent or how to use it in a way where I can retrieve records with concrete parent_id ?

Answer Source

Your query should be like this:

$services = $category->services()->where('parent_id', 0)->get()