如何获得表1中的所有人,而不获得表2中以我为parent_id的人



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

这是我目前拥有的结构:

第一张表:-id-名称-。。。

第2张表:-parent_id-child_id

知道parent_ id和child_id对应于同一个表。以下是链接它们的功能

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

目前,对于搜索系统,我希望获得表1中的所有人,而不获得表2中以我为parent_id的人。

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

人员模型

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

控制器

public function test()
{
$myId = 1;
$persons = AppModelsPerson::whereDoesntHave('parents')
->orWhereHas('parents', function($qry) use($myId){
$qry->where('person_relations.parent_id', '!=', $myId);
})
->get();
}

此方法将返回所有没有给定$myId作为其父id的记录。

在Laravel 6.2和7.29 中测试和工作

相关内容

最新更新