【问题标题】:many to many issues with eloquent while using pivot table使用数据透视表时 eloquent 的多对多问题
【发布时间】:2015-07-30 12:44:34
【问题描述】:

我有 3 张桌子。用户、主题和主题用户。这是因为我需要多对多的关系。我在两个模型中都创建了以下内容:

// Theme.php

public function users() { return $this->belongsToMany('App\User', 'theme_user', 'theme_code', 'user_id'); }

//用户.php

public function themes() { return $this->belongsToMany('App\Theme', 'theme_user', 'user_id', 'theme_code'); }

现在我想从某个主题中获取所有用户。所以我愿意

$themeUser = Theme::where('code', '=', $code)->first()->users;

但是我得到的查询不正确..

'select users.*, theme_user.theme_code as pivot_theme_code, theme_user.user_id as pivot_user_id from users inner join theme_user on users.id = theme_user.user_id where theme_user.theme_code is null'

我该如何解决这个问题?

【问题讨论】:

  • 查询有什么问题?
  • 嗯.. 我需要获取分配给主题的用户。使用这个查询我没有得到那个结果。
  • 一切看起来都正确。我能想到的唯一会导致这种情况的是,如果找到的Theme 记录的theme_code 为空。你从dd(Theme::where('code', '=', $code)->first()); 得到什么?

标签: php database laravel database-design laravel-5


【解决方案1】:

查看有关 hasManyThrough() 的文档:http://laravel.com/docs/4.2/eloquent#has-many-through

在你的情况下,它会是这样的:

class User
{
    public function themes()
    {
        return $this->hasManyThrough('ThemeUser', 'Theme');
    }
}

【讨论】:

  • 不需要hasManyThrough这只是数据透视表的一个例子
  • 但是我必须创建一个 ThemeUser 模型?那是两个模型中的一个模型。不要认为这真的是最佳实践吗?
猜你喜欢
  • 1970-01-01
  • 2014-12-07
  • 2023-02-05
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2015-02-04
  • 2019-10-06
  • 1970-01-01
相关资源
最近更新 更多