Laravel通过hasMany获得belongsToMany

时间:2014-06-12 10:58:13

标签: laravel laravel-4

我有3个模型:ConferenceSessionSpeaker。会议可以有很多会议,很多会议可以有很多演讲者。

数据库结构

conferences
-----------
id
name


sessions
--------
id
conference_id
name


session_speaker
---------------
id
session_id
speaker_id


speakers
--------
id
name

我需要编写一种方法,让我能够得到特定会议的所有发言者(所有发言人都来自该会议的所有会议)。

以下说明了我认为应该工作的内容,但显然不能解决这些问题。

应用程序/模型/ Conference.php

class Conference extends Eloquent {

  public function speakers() {
    return $this->hasMany('Session')->belongsToMany('Speaker');
  }

}

我已经建立了所有模型 - 模型关系并且工作正常(会议 - 会话,会话 - 演讲者)但是我无法在会议 - 会话 - 演讲者之间建立桥梁。有没有人知道如何在不编写大型SQL连接查询的情况下实现这一目标?

我认为,如果存在关系belongsToManyThrough(),这将有效,但是没有。

提前致谢!

1 个答案:

答案 0 :(得分:7)

不幸的是,hasManyThrough关系不适用于它们之间的多对多关系。

你可以做的是这样的事情:

public function speakers() {
  $session_ids = Session::where('conference_id', $this->id);
  $speaker_ids = DB::table('session_speaker')->whereIn('session_id', $session_ids)->lists('speaker_id');
  return Speaker::whereIn('id', $speaker_ids)->get();
}

如果没有找到结果,您可能需要将变量设置为array(0),否则whereIn函数将引发错误。 您也可以使用Eloquent-only方式,但这可能会导致更多的数据库查询,而这一个应该可以正常运行。

然后您可以使用以下方式访问扬声器Conference::find(1)->speakers()