Laravel5.5 多对多关联,怎么优雅的取数据?

手册看了,好像没有帮助我太多,求助各位大神给个最优雅的方式哈。。

现在有三个表,group群组表,authority权限表,group_authority关系表,

我现在的任务是写一个Policy权限认证,从group_authority中间关系表中搜寻group_id是否有对应的authority_id,如果有,说明有权限,如果没有对应的authority_id说明没有权限。

如果直接用DB:table(中间表),这样查询起来感觉不优雅。求教各位大神,是如何用ORM查询呢?或者有什么方法呢? 最好来个代码秀一下,让小弟长长见识哈。

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
Epona
最佳答案
class Group
{
    public function authorities()
    {
        return $this->belonsToMany(Authority::class);
    }
}

class Authority
{
    public function groups()
    {
        return $this->belonsToMany(Group::class);
    }
}

$exists = Group::query()
    ->whereHas('authorities', function($query) {
        $query->where('id', '你想要查询的authority id');
    })->exists();
4年前 评论
qIXbwU11 (楼主) 4年前
Alex_lcl 4年前
讨论数量: 1
Epona
class Group
{
    public function authorities()
    {
        return $this->belonsToMany(Authority::class);
    }
}

class Authority
{
    public function groups()
    {
        return $this->belonsToMany(Group::class);
    }
}

$exists = Group::query()
    ->whereHas('authorities', function($query) {
        $query->where('id', '你想要查询的authority id');
    })->exists();
4年前 评论
qIXbwU11 (楼主) 4年前
Alex_lcl 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!