如何在不让表2中拥有我的人作为父母的情况下获得表1中的所有人?

问题描述

我写这篇文章是因为我与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的人员成为我。

解决方法

我已经向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中经过测试并可以正常工作