【问题标题】:Laravel HasManyThrough deep relationshipLaravel HasManyThrough 深度关系
【发布时间】:2021-12-06 07:05:43
【问题描述】:

我有一个多租户设置,其中一个租户 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)

提前致谢!

【问题讨论】:

  • “workspaces”和“students”表(类似于“student_workspace”)之间是否有中间(数据透视)表?我假设您也应该拥有该数据透视表,因为我认为任何工作区都可以有多个学生,每个学生都可以有多个工作区。我说的对吗??

标签: php laravel database eloquent relation


【解决方案1】:

您可以通过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());
    }

}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2023-03-09
    • 2018-07-24
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2018-03-08
    • 2023-03-08
    相关资源
    最近更新 更多