[英]Laravel HasManyThrough deep relationship
我有一个多租户设置,其中一个租户HasMany
工作空间和工作空间BelongsToMany
学生。 如何从租户创建关系,从中检索租户内所有工作区的所有学生?
我查看了hasManyThrough
但这并不能解决问题。 现在我有这个功能:
public function getStudents()
{
$this->workspaces()->get()->map(function ($workspace) {
return $workspace->students;
})->flatten()->unique();
}
但我想用关系而不是上面的代码来做。 有什么建议吗?
Tenant :HasMany=> Workspace(tenant_id) :BelongsToMany=> Student(student_workspace table)
提前致谢!
你可以通过join
来做到这一点:
public function students(){
return Student::select('students.*')
->join('student_workspace', 'students.id', '=', 'student_workspace.student_id')
->join('workspaces', 'workspaces.id', '=', 'student_workspace.workspace_id')
->join('tenants', 'tenants.id', '=', 'workspaces.tenant_id')
->where('tenants.id', $this->id);
}
或者像使用这个包的任何正常关系一样: hasManyDeep通过以下步骤:
第一的:
composer require staudenmeir/eloquent-has-many-deep
在您的Workspace
模型文件中:
public function students()
{
return $this->belongsToMany(Student::class, 'student_workspace');
}
在您的Tenant
模型文件中:
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
class Tenant extends Model
{
use HasFactory, HasRelationships;
public function students(){
return $this->hasManyDeepFromRelations($this->workspaces(), (new Workspace)->students());
}
}
希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.