2015-05-18 54 views
1

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

我該如何解決這個問題?

+0

這有什麼錯查詢? – patricus

+0

那麼..我需要獲得分配給主題的用戶。有了這個查詢,我沒有得到那個結果。 – Reshad

+0

一切看起來都正確。我能想到的唯一情況就是如果找到的'Theme'記錄的'theme_code'爲null。你從dd得到了什麼(主題:: where('code','=',$ code) - > first());'? – patricus

回答

0

檢查出hasManyThrough的文檔():http://laravel.com/docs/4.2/eloquent#has-many-through

在你的情況,這將是這樣的:

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

沒有hasManyThrough的要求,這只是一個數據透視表 –

+0

的情況下,但後來我必須創建一個ThemeUser模型?這是來自兩個模型的模型..不認爲這真的是一個最佳實踐嗎? – Reshad

相關問題