【问题标题】:Laravel's Eloquent pivot objectLaravel 的 Eloquent 枢轴对象
【发布时间】:2015-01-01 10:44:37
【问题描述】:

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

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
            }
        ],

【问题讨论】:

  • 显示是指将其转换为数组/JSON 吗?

标签: laravel-4 eloquent pivot-table


【解决方案1】:

使用accessor:

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

然后你可以像访问其他属性一样访问它:

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

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

protected $appends = ['season'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2019-07-27
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2019-08-25
    • 1970-01-01
    相关资源
    最近更新 更多