记录值不等于当前值

时间:2016-12-19 17:57:44

标签: laravel eloquent laravel-5.3

我有7 DepartmentsEmployee通过名为DepartmentItem的多态连接模型分配给其中的2个$employee = \App\Employee::find(1); $departments = \App\Department::join('department_items', 'department_items.department_id', '=', 'departments.id') ->select('departments.*') ->groupBy('departments.id') ->where('company_id', $employee->company_id) ->where('department_items.item_id', '!=', $employee->id) ->where('department_items.item_type', 'employee') ->get(); dd($departments); 。当我运行以下内容时,我希望获得该员工不属于的5条记录,而是获得所有7条记录。

'!='

当它应该只返回5时返回7个部门。当我将'='更改为// Company public function departments() { return $this->hasMany(Department::class); } public function employees() { return $this->hasMany(Employee::class); } // Department public function company() { return $this->belongsTo(Company::class); } public function employees() { return $this->morphedByMany(Employee::class, 'item', 'department_items'); } // DepartmentItem public function department() { return $this->belongsTo(Department::class); } public function item() { return $this->morphTo(); } // Employee public function company() { return $this->belongsTo(Company::class); } 时,它将返回员工分配到的2个部门。

以下是模型关系:

flex-grow

1 个答案:

答案 0 :(得分:0)

您应该使用<>而不是!=,因为where clause方法需要使用mysql运算符。

所以你的代码应该是这样的:

$departments = \App\Department::join('department_items', 'department_items.department_id', '=', 'departments.id')
    ->select('departments.*')
    ->groupBy('departments.id')
    ->where('company_id', $employee->company_id)
    ->where('department_items.item_id', '<>', $employee->id)
    ->where('department_items.item_type', 'employee')
    ->get();

希望这有帮助!