TL/DR:withPivot
我使用and 和
的两个模型之间建立了多对多的关系using
。我想withPivot
从外键的值中获取相关数据。
我正在处理一个多租户项目,该项目有一个master
数据库和tenant
数据库。
中的任何模型App\Tenant\
当前都在使用该$connection
属性。
我的模型及其关联表具有以下结构:
- App/Tenant/Match
- App/Tenant/MatchTeam
- App/Team
- App/Ground
team
和之间的关系match
是many-to-many
(ateam
可以玩多个matches
,amatch
可以有很多teams
)
匹配.php
namespace App\Tenant
class Match extends TenantModel
public function teams() {
return $this->belongsToMany(Team::class, 'tenant.match_team', 'match_id', 'team_uuid')
->using(MatchTeam::class)
->withPivot('ground_id');
}
团队.php
namespace App
class Team extends Model
protected $primaryKey = 'uuid';
public $incrementing = false;
public function grounds() {
return $this->hasMany(Ground::class, 'team_uuid', 'uuid');
}
public function matches() {
return $this->belongsToMany(Match::class, 'tenant.match_team', 'team_uuid', 'match_id')
->using(MatchTeam::class)
->withPivot('ground_id')
;
}
MatchTeam.php
class MatchTeam extends Pivot
protected $connection = 'tenant';
protected $table = 'match_team';
public function ground() {
return $this->hasOne(Ground::class);
}
match_team 表:
| id | team_uuid | match_id | ground_id |
|----| ------------------ | -------- | --------- |
| 1 | kajdnfgkasdnfadsgn | 1 | NULL |
| 2 | lsdjfgsadlkfjglsdj | 2 | 4 |
| 2 | kshdfkjdshfytufjek | 3 | 1 |
问题:
如何访问与数据透视表ground_id
上的字段相关的地面数据?match_team
我主要追求的是类似于表match->ground->name
上外键的关系match_team
。
我尝试了以下方法:
匹配控制器.php
public function show(Match $match) {
$match = Match::where('id', $match->id)->with('ground')->first();
}
但它给Call to undefined relationship [ground]
DD($match) 如下要求
Interaction {#215 ▼
#table: "matches"
#connection: "tenant"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:19 [▶]
#original: array:19 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"ground" => null
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}