我有一個多租戶設定,其中一個租戶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)
提前致謝!
uj5u.com熱心網友回復:
您可以通過以下方式做到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());
}
}
希望這會有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326508.html
