Laravel从表中获取所有记录,但已在数据透视表中关联的记录除外

时间:2020-04-29 14:08:04

标签: laravel eloquent

我有三个表:

餐桌部门:

|------|-------------|
|  id  |     name    |
|------|-------------|
|  1   | Department1 |
|  2   | Department2 |
|  3   | Department3 |
|------|-------------|

表组:

|------|--------|
|  id  |  name  |
|------|--------|
|  1   | Group1 |
|  2   | Group2 |
|------|--------|

表部门组:

|------|---------------|---------------|
|  id  |    group_id   | department_id |  
|------|---------------|---------------|
|  1   |       1       |       1       |
|  2   |       2       |       2       |
|------|---------------|---------------|

我需要从部门表中获取所有与Department_group表中的group_id 1没有关联的记录。 因此,在此示例中,我想要Group1的Department2和Department3以及Group2的Department1和Department3。

我知道如何为此编写MySql查询,但是有一种使用雄辩关系的方法吗?

预先感谢您的回答 法比奥

编辑: 这些模型是:

class Group extends Model
{
    protected $table = 'groups';

    protected $fillable = [
        'name'
    ];

    public function departmentGroups() {
        return $this->hasMany(DepartmentGroup::class, 'group_id','id');
    }



class Department extends Model
{
    protected $table = 'departments';

    protected $fillable = [
        'name'
    ];

    public function departmentGroups() {
        return $this->hasMany(DepartmentGroup::class, 'department_id','id');
    }

1 个答案:

答案 0 :(得分:2)

您需要具有适当的Many to Many关系(https://laravel.com/docs/7.x/eloquent-relationships#many-to-many),然后可以轻松使用whereDoesntHave()

class Group extends Model
{
    ...
    public function departments() {
        return $this->belongsToMany(Department::class, 'department_group');
    }
}


class Department extends Model
{
    ...
    public function groups() {
        return $this->belongsToMany(Group::class, 'department_group');
    }

    $departmentsNotAssociated = Department::whereDoesntHave('groups', function($query) {
        $query->where('id', '=' , 1)
    })->get();

您可以在文档中进一步了解它:https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-absence