我在我的模型中定义了关系:
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
}
],
答案 0 :(得分:1)
使用accessor:
public function getSeasonAttribute()
{
return ($this->pivot) ? $this->pivot->season : null;
}
然后您可以像其他属性一样访问它:
$position = $someModel->positions->first();
$position->season;
如果您在toArray/toJson
输出中也需要它,那么请使用您的模型:
protected $appends = ['season'];