具有多对多和自参考的Laravel/Elount模型
一个办公室有很多员工,一个员工可以在多个办公室工作具有多对多和自参考的Laravel/Elount模型,laravel,eloquent,Laravel,Eloquent,一个办公室有很多员工,一个员工可以在多个办公室工作 // office model public function employees() { return $this->belongsToMany(Model\Employee::class); } // employee model public function offices() { return $this->belongsToMany(Model\Office::class); } 使用此选项,我可以得
// office model
public function employees()
{
return $this->belongsToMany(Model\Employee::class);
}
// employee model
public function offices()
{
return $this->belongsToMany(Model\Office::class);
}
使用此选项,我可以得到一个关系,进一步筛选如下:
$qualified = $office->employees()->whereHas('qualifications', function ($query) {
$query->whereIn('job', ['doctor', 'dentist']);
});
// office model
public function inheritedEmployees()
{
$employees = collect();
if ($this->is_major) return $employees;
foreach ($this->majors as $major) {
$employees->concat($major->employees);
}
return $employees->unique('id')->sortBy('first_name');
}
困难在于,一些办公室太小,无法拥有自己的员工,因此我们将他们“附加”到一个或多个大型办公室,让他们“继承”这些员工。我们把小办公室称为“小办公室”,把大办公室称为“大办公室”
// office model
public function majors() {
return $this->belongsToMany(Model\Office::class, 'attachments', 'minor_id', 'major_id');
}
在处理小型(即“次要”)办公室时,我需要能够访问他们继承的员工。我已设法做到以下几点:
$qualified = $office->employees()->whereHas('qualifications', function ($query) {
$query->whereIn('job', ['doctor', 'dentist']);
});
// office model
public function inheritedEmployees()
{
$employees = collect();
if ($this->is_major) return $employees;
foreach ($this->majors as $major) {
$employees->concat($major->employees);
}
return $employees->unique('id')->sortBy('first_name');
}
问题是,inheritedEmployees()
不会返回雄辩的关系,因此我无法向其中添加其他子句
如何更改
inheritedEmployees()
以返回关系?您不需要实际返回关系来将方法链接到它;任何尚未执行的查询都将返回一个QueryBuilder
,您可以链接它
假设您拥有反向subjectors()
关系(获取主办公室下的办公室),您可以尝试执行以下操作:
// In the Office model
public function inheritedEmployees() {
return EmployeeAssignment::query()
->where('office_id', $this->minors()->pluck('id'));
}
我假设您创建了一个helper(
EmployeeAssignment
)类来模拟办公室和员工之间的数据透视表(这对于处理像这样的复杂关系很有用)。您不能。您不能引用$this
,引用模型实例并返回关系。因为在关系上下文中,$this
是一个查询对象,而不是模型的实例。谢谢DfKimera,这让我高兴极了!