Laravel 的 Eloquent 枢轴对象

Laravel's Eloquent pivot object

我已经在我的模型中定义了关系:

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

是否可以以更简洁的方式显示带枢轴的对象? 例如:

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

我想得到:

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

使用accessor:

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

然后您就可以像访问其他属性一样访问它了:

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

如果您在 toArray/toJson 输出中也需要它,请在您的模型上使用:

protected $appends = ['season'];