复杂的多层次Laravel4雄辩关系

时间:2014-08-01 01:00:57

标签: laravel laravel-4 eloquent

我正在尝试打印一个页面,其中显示了注册活动的所有用户。如果用户有权参加,则用户被定义为“高级职员”,每位高级职员都是学生(但学生可以是多个俱乐部中任何职位的高级职员)。

以下是我的关系:

class OfficerEvent extends Eloquent{

protected $table = "officerEvents";
public $timestamps = false; 
protected $primaryKey = "oeventID";

public function rsvp()
{
    return $this->hasMany('OfficerEventRSVP', 'oeventID');
} 
 }

官员RSVP参加活动:

class OfficerEventRSVP extends Eloquent{

protected $table = "officerEventRSVP";
public $timestamps = true; 
protected $primaryKey = "rsvpID";

public function officerEvent()
{
    return $this->belongsTo('OfficerEvent', 'oeventID');
}

public function officer()
{
    return $this->belongsTo('Officer', 'cwid', 'officerCWID');
}
}

官员表:

class Officer extends Eloquent{

protected $table = "officers";
public $timestamps = false;
protected $primaryKey = "cwid";

public function club()
{
    return $this->belongsTo('Club', 'clubID');
}

public function student()
{
    return $this->belongsTo('Student', 'cwid');
}

public function officerEventRSVP()
{
    return $this->hasMany('OfficerEventRSVP', 'cwid', 'officerCWID');
}

} 

学生表(所有官员都是学生):

class Student extends Eloquent{

protected $table = "students";
public $timestamps = false;
protected $primaryKey = "cwid";

public function officer()
{
    return $this->hasMany('Officer', 'cwid', 'cwid');
}

}

我正试图查询a)获取所有事件和rsvps,然后b)从这些RSVP获取官员信息(姓名,电子邮件)。

到目前为止我已经得到了这个,但是当我运行它时,我一直得到一个白页:

    $officerEvents = OfficerEvent::with('rsvp')->get();

    foreach($officerEvents as $officerEvent)
    {
     foreach ($officerEvent->rsvp as $rsvp) {
        foreach ($rsvp->officer() as $officer) {
            var_dump($officer->student());
        }
      }   
    }

1 个答案:

答案 0 :(得分:0)

如果每个官员都是学生,那么关系是hasOne,而不是hasMany。语法保持不变,但它希望直接一对一连接。

您是否正确地将这些密钥设置为迁移中的索引?