我多对多关系,获取数据透视表的ID

时间:2019-05-04 11:15:02

标签: laravel

我具有以下多对多关系模型:

class Event extends Model
{
    public function positions() {
        return $this->belongsToMany(Position::class, 'position_events');
    }
}

class Position extends Model
{
    public function events() {
        return $this->belongsToMany(Event::class, 'position_events');
    }
}

class PositionEvent extends Model
{
    public function position() {
        return $this->hasOne(Position::class, 'id', 'position_id');
    }

    public function event() {
        return $this->hasOne(Event::class, 'id', 'event_id');
    }
}

position_events表如下:

id | event_id | position_id

如果$eventEvent的实例,我可以得到以下相关职位:

$event->positions;

这给我每个相关职位以下的东西:

{"id":4,"name":"Striker","created_at":"2019-04-02 16:19:57","updated_at":"2019-04-02 16:19:57","pivot":{"event_id":27,"position_id":4}}  

注意pivot元素。它仅具有event_idposition_id作为属性,它们是position_events表中的列。如何获得该表中的id列?

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用withPivot(),例如:

$this->belongsToMany(Position::class, 'position_events')->withPivot('id');