Tuesday, February 28, 2017

Eloquent Showing pivot

for some weird reason building this model with Eloquent is hiding the Pivot that I am requiring explicitly in the relation (This Model is called Match):

public function scorers()
{
    return $this->belongsToMany(
        Player::class,
        'match_players',
        'match_id'
    )->withPivot(
        'goals'
    )->where(
        'goals', '>', 0
    );
}

public function scopeComplete($query)
{
    return $query->with(
        'homeTeam',
        'awayTeam',
        'scorers'
    );
}

The problem is the json result of scorers is as follows

"scorers": [
  {
    "id": 196,
    "name": "Tino",
    "surname": "Heck",
    "age": 24
  },...

And is hiding the pivot (goals) team_id and goals which should appear on each object inside a nested object called pivot, did anyone came across some problem like this? I cat find anything around here. Something like

"scorers": [
  {
    "id": 196,
    "name": "Tino",
    "surname": "Heck",
    "age": 24,
    "pivot": {
      "goals": 3
    }
  },...

Db structure is

Match
- id
- ..
Players
- id
- ...
MatchPlayer
- player_id
- match_id
- goals

The result inside scorers is correct, so I get the actual player where goals > 0, but not the pivot I am looking for

Thanks in advance.




via vikkio

Advertisement