【问题标题】:How to compact two relationship in one relationship如何在一个关系中压缩两个关系
【发布时间】:2016-01-20 12:06:21
【问题描述】:

当我想在 Laravel 中压缩两个关系时,我遇到了一些问题。 有 3 个带模型的表。

table1: episodes --> model: Episode
      relations -- hasMany --> posts
               -- belongsToMany --> users

pivot-table2: posts    --> model: Post
      columns -- episode_id
              -- user_id
      relations  -- belongsTo --> user
                 -- belongsTo --> episode

table3: users    --> model: User

是的,这是一个多对多的关系。我们可以在 Episode 模型上获取帖子或用户关系。

如果我有一个模型集合

$episode = new App\Episode

它怎么会像这样急切地加载

$episodes = new App\Episode::with('posts.user').

也许我可以像下面那样做

$episode = new App\Episode::with('posts.user')->where('id','=','targetId')

但似乎会先连接三个表,然后进行查询以获取目标剧集。

有什么方法可以像

 $episode = new App\Episode::find(targetId)-> with('posts.user')

【问题讨论】:

  • Posts 表中应该有 user_id 列。
  • @Ehs4n 抱歉,这是我的错误。

标签: laravel eloquent


【解决方案1】:

如果您将帖子表用作数据透视表,那么您做错了。

剧集模型:

public function users()
{
    return $this->belongsToMany('App\User', 'posts');
}
// I would name my pivot table different than posts, if you don't pass the second parameter Laravel will look for episode_user table 

用户模型:

public function episodes()
{
    return $this->belongsToMany('App\Episode', 'posts');
}

在您的控制器中:

$user = User::find(1);
$user->episodes();

$episodes = Episode::find(1);
$episodes->users();

【讨论】:

  • 感谢您的回复。
  • @Ionut Neculcea 感谢您的回复。我知道这些关系,但我只是在我的例子中忽略了它们。我想弄清楚如何急切加载单个 Post 模型而不是 Posts modelCollections。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多