使用数据透视表时,很多问题都是雄辩的

时间:2015-05-18 21:14:19

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

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

// Theme.php

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

// User.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'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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

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