【问题标题】:Get all related users that don't relate to a certain relation获取与特定关系无关的所有相关用户
【发布时间】:2021-12-14 14:07:50
【问题描述】:

我有 4 个表,分别是用户表、规则表、rule_requests 表和 rule_employee 表。查找下表。

用户表

id name
10 test1
12 test2
13 test3

规则

id active
1 true
2 true

规则请求

rule_id request_type
1 Normal leave
2 Sick leave

规则员工表

id user_id
1 10
2 12

每个用户可能有一个规则,每个规则必须至少有 1 个请求类型。我想要做的是让所有没有特定请求类型规则的用户。例如,如果我想要所有没有 'sick leave' 请求类型规则的用户,我应该得到 10 和 13。 最好的方法是什么?

【问题讨论】:

  • 您将使用带有 JOIN 的 SELECT 查询,也许还有一个子查询;但确切的语法取决于您使用的数据库系统类型以及表和字段的确切名称
  • 能否在表格中指定PK和FK?规则和员工之间的联系在哪里?

标签: php laravel


【解决方案1】:

我注意到你把这个问题放在 Laravel 标记中,所以在 Laravel 中的答案是...... 模型用户和规则将通过belongsToMany 关系建立支点关系

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

然后调用用户模型如..

$filter_role_id = 2; // id of sick leave
$location_other_listings = User::whereDoesntHave([
        'roles' => function($query) use ($filter_role_id){
            $query->where('id', $filter_role_id);
        }
    ])
    ->get();

这应该得到所有没有该特定角色的用户

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2014-09-17
    • 2013-05-23
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多