[英]Laravel HasManyThrough deep relationship
I have a multi-tenant setup where a tenant HasMany
workspaces and a workspace BelongsToMany
students.我有一个多租户设置,其中一个租户
HasMany
工作空间和工作空间BelongsToMany
学生。 How do I create a relationship from the tenant where I retrieve all the students from all workspaces within the tenant?如何从租户创建关系,从中检索租户内所有工作区的所有学生?
I've took a look at hasManyThrough
but that does not solve the problem.我查看了
hasManyThrough
但这并不能解决问题。 Right now I have this function:现在我有这个功能:
public function getStudents()
{
$this->workspaces()->get()->map(function ($workspace) {
return $workspace->students;
})->flatten()->unique();
}
But I'd like to do it in a relation instead of the above code.但我想用关系而不是上面的代码来做。 Any advice?
有什么建议吗?
Tenant :HasMany=> Workspace(tenant_id) :BelongsToMany=> Student(student_workspace table)
Thanks in advance!提前致谢!
You could do it through join
like:你可以通过
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);
}
Or like any normal relation using this package: hasManyDeep through the following steps:或者像使用这个包的任何正常关系一样: hasManyDeep通过以下步骤:
First:第一的:
composer require staudenmeir/eloquent-has-many-deep
In your Workspace
model file:在您的
Workspace
模型文件中:
public function students()
{
return $this->belongsToMany(Student::class, 'student_workspace');
}
In your Tenant
model file:在您的
Tenant
模型文件中:
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
class Tenant extends Model
{
use HasFactory, HasRelationships;
public function students(){
return $this->hasManyDeepFromRelations($this->workspaces(), (new Workspace)->students());
}
}
Hope this would be helpful.希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.