0

我写这篇文章是因为我在 Laravel 上的关系有问题。

这是我目前拥有的结构:

第一个表: - id - 名称 - ...

第二张表: - parent_id - child_id

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

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

目前,对于搜索系统,我想在表 1 中获取所有人,而不是在表 2 中获取以我为 parent_id 的人。

4

1 回答 1

0

我添加了与模型的反比关系parents()People而不是问题中的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();
    }

此方法将返回所有没有给定$myId父 ID 的记录。

在 Laravel 6.2 和 7.29 中测试和工作

于 2020-11-09T21:02:49.720 回答