/ / Laravel Eloquent Pivot-Objekt - Laravel-4, eloquent, Pivot-Tisch

Laravel Eloquent Pivot Objekt - Laravel-4, eloquent, Pivot-Tisch

Ich habe eine Beziehung in meinem Modell definiert:

public function positions() {
return $this->belongsToMany("Position", "users_positions")->withPivot("season");
}

Kann man Objekte mit Pivot übersichtlicher darstellen? Zum Beispiel:

"positions": [
{
"id": 1,
"name": "A",
"pivot": {
"user_id": 1,
"position_id": 1,
"season": 2014
}
}
],

Ich hätte gern:

"positions": [
{
"id": 1,
"name": "A",
"season": 2014
}
],

Antworten:

1 für die Antwort № 1

Benutzen Accessor:

public function getSeasonAttribute()
{
return ($this->pivot) ? $this->pivot->season : null;
}

Dann können Sie wie andere Eigenschaften darauf zugreifen:

$position = $someModel->positions->first();
$position->season;

wenn sie es auch brauchen in der toArray/toJson Ausgabe, dann verwenden Sie auf Ihrem Modell:

protected $appends = ["season"];