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

I have 3 tables. user, theme and theme_user. Its because I need a many to many relationship. I created in both the models the following:

// 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'); }

Now I want to get all users from a certain theme. Therefor I do

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

But the query I get is not right..

'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'

How can I solve this?

Check out the documentation on hasManyThrough(): http://laravel.com/docs/4.2/eloquent#has-many-through

In your case, it would be something like:

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