簡體   English   中英

Laravel HasManyThrough 深厚的關系

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM