Svyat Svyat - 26 days ago 9
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):

services:
id
name
parent_id


parent_id is FK to the same table (FK to services.id).

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

Your query should be like this:

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