【发布时间】:2019-06-14 10:30:16
【问题描述】:
TL/DR:
我使用withPivot 和using 在两个模型之间建立了多对多关系。我想从外键的withPivot 值中获取相关数据。
我正在处理一个多租户项目,该项目有一个master 数据库和tenant 数据库。
App\Tenant\ 中的任何模型当前都在使用$connection 属性。
我的模型及其关联表的结构如下:
- App/Tenant/Match
- App/Tenant/MatchTeam
- App/Team
- App/Ground
team和match的关系是many-to-many
(一个team可以播放多个matches,一个match可以播放多个teams)
Match.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');
}
Team.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 |
问题:
如何访问与 match_team 数据透视表上的 ground_id 字段相关的地面数据?
我主要关注match->ground->name 之类的东西,它是match_team 表上外键的关系。
我尝试了以下方法:
MatchController.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 [▶]
}
【问题讨论】:
-
我也试过
$match->pivot->ground_id,但得到了同样的错误。 -
当你看到地面是空的,所以尝试重构
Match模型中的ground关系 -
Match 模型没有
ground_id字段。那是枢轴上的数据。 -
使用
BelongsToMany关系时只能访问pivot关系:foreach ($match->teams as $team) { $team->pivot->ground->name; }
标签: laravel eloquent pivot eloquent-relationship