在Laravel 5.2中,不能在同一个表上使用外键检索记录


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

我使用Laravel 5.2从数据库检索记录。

My table(简化):

services:
id
name
parent_id

parent_id是同一个表的FK (FK到services.id)。

这段代码返回一个空集合:

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

Select with other where condition工作正常。交货。

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

返回非空结果。

原始SQL也可以正常工作:

SELECT * FROM services WHERE parent_id = 0;

什么是错的雄辩或如何使用它的方式,我可以检索记录与具体的parent_id ?

你的查询应该是这样的:

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