Laravel属于ToMany关系返回第三列

时间:2014-06-29 18:19:33

标签: php laravel-4 eloquent

我正在尝试将部分表单数据保存到数据透视表中。这在保存时工作正常,但在获得关系时我无法重试第三列(活动布尔值)。

class _Event extends Eloquent {
    protected $table = 'events';

    public function groups()
    {
        return $this->belongsToMany('Group', 'events_groups', 'event_id', 'group_id');
    }
}

class Group extends Eloquent {
    public function events()
    {
        return $this->belongsToMany('_Event', 'events_groups', 'group_id', 'event_id')->where('events_groups.active', 1);
    }
}

运行dd (_Event::with('groups')->find($event_id));让我:

array(11) {
    ["id"] "1"
    ["groups"] array(2) {
        [0] array(4) {
            ["id"] "3"
            ["admin"] "0"
            ["pivot"] array(2) {
                ["event_id"] "1"
                ["group_id"] "3"
            }
        }
        [1] array(4) {
            ["id"] "4"
            ["admin"] "0"
            ["pivot"] array(2) {
                ["event_id"] "1"
                ["group_id"] "4"
            }
         }
    }
}

我的数据库设置如下(删除了不相关的列):

events : id
groups : id - admin
events_groups : id - event_id - group_id - active

如何检索active列?

1 个答案:

答案 0 :(得分:1)

您需要withPivot()方法。

来自the documentation

  

默认情况下,只有键才会出现在数据透视对象上。如果数据透视表包含额外属性,则必须在定义关系时指定它们:

return $this->belongsToMany('Role')->withPivot('foo', 'bar');
     

现在,我们可以在角色模型的数据透视对象上访问foo和bar属性。