从多对多数据透视表上的withPivot获取关系数据

时间:2019-06-14 10:30:16

标签: laravel eloquent pivot eloquent--relationship

TL / DR: 我在两个使用withPivotusing的模型之间建立了多对多关系。我想从外键的withPivot值中获取相关数据。


我正在处理一个多租户项目,该项目有一个master数据库和tenant数据库。

App\Tenant\中的任何模型当前都使用$connection属性。

我的模型及其关联表具有以下结构:

- App/Tenant/Match
- App/Tenant/MatchTeam
- App/Team
- App/Ground

teammatch之间的关系为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);
}

比赛团队表:

| 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表上外键的关系。


我尝试了以下操作:

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 [▶]
}

1 个答案:

答案 0 :(得分:0)

正如您的错误所说,匹配模型中没有地面关系 因此,在您的匹配模型

public function ground() {
    return $this->hasOne(Ground::class,'foreign_key', 'local_key');
}

编辑

由于我不知道表结构

可能会帮助您

  

方法一:

if(! is_null($match->pivot->ground))
{
  $groundName = $match->pivot->ground->name;
}else{
    $groundName = 'Ground Not Set';
}
  

方法二:

$groundName = $match->ground['name'] ??  'Ground Not Set';