如何让 table 1 中的所有人都得到,而不让 table 2 中有我的 parent_id 的人?

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

我写这个 post 是因为我在 Laravel.

上的人际关系有问题

这是我目前的结构:

第一 table: - ID - 姓名 - ...

第二 table : - parent_id - child_id

知道parent_id和child_id对应同一个table。这是链接它们的函数

public function relation()
{
    return $this->belongsToMany('App\Person', 'person_relations', 'parent_id', 'child_id', 'id', 'id');
}

目前我想,对于一个搜索系统,得到 table 1 中的所有人,而不是 table 2 中的 parent_id 的人。

我在 People 模型中添加了一个反关系 parents() 而不是问题中的 relation() 方法。

人物模型 :

public function parents()
{
    return $this->belongsToMany('App\Models\Person', 'person_relations', 'child_id', 'parent_id', 'id', 'id');
}

控制器 :

public function test()
{
    $myId = 1;

    $persons = \App\Models\Person::whereDoesntHave('parents')
        ->orWhereHas('parents', function($qry) use($myId){
            $qry->where('person_relations.parent_id', '!=', $myId);
        })
        ->get();
    }

此方法将 return 所有没有给定 $myId 作为其父 ID 的记录。

在 Laravel 6.2 和 7.29

中测试和工作