2016-06-10 90 views
1

Okey,我是Laravel的新手,我想在我的控制器中執行一個函數,該函數返回一個JSON與一個用戶的所有列表,我想通過電子郵件過濾用戶,這不是主鍵,但我在這裏遇到很多問題,laravel的文檔沒有解釋這一點。Laravel 5.2按用戶篩選或列出來自用戶的所有列表

奧基,所以我有這個atributes和關係的一類用戶:

user.php的

protected $fillable = [ 
    'nom', 'email', 'password', 'data_de_naixament', 'sexe', 'type', 'imatge_usr', 'codi_postal' 
]; 

public function lists() 
{ 
    return $this->hasMany('App\List'); 
} 

而另一類List:

list.php的

protected $fillable = ['nom_llista', 'id_user']; 

public function user() 
{ 
    return $this->belongsTo('App\User', 'id_user'); 
} 

所以我知道我必須做一個JOIN並將輸入參數與用戶表的電子郵件列表進行比較,但我無法得到它,因爲他們根本不理解句法雄辯。

我能夠做一個函數來存儲所有列表,然後通過電子郵件進行過濾,但是如果我有2000個列表,例如這不是有效的。

希望你能幫助我,對我可憐的英語感到抱歉。

+0

如果您執行'$ user-> whereEmail('[email protected]') - > first() - > lists()',您將獲得該用戶的所有列表。這是你想要做的嗎? – TheFallen

+0

它一直沒有工作,「數據」返回null,但下面的答案工作,無論如何,謝謝! – Aleix

回答

0

你應該閱讀文檔

檢索信息:https://laravel.com/docs/5.1/eloquent#retrieving-multiple-models

到集合轉換成JSON:https://laravel.com/docs/5.1/collections#method-tojson

加盟模式: https://laravel.com/docs/5.1/eloquent-relationships#querying-relations

換句話說,你的代碼可能是像

$users = User::where('email', $emailYouAreLookingFor)->with('lists')->get()->toJson(); 
+0

它的工作原理,但我有問題的名稱id_user,我改名爲user_id,現在它的作品,謝謝你! – Aleix

+0

太好了,但它並不是必需的,你可以指定外鍵和本鍵的名稱https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships [return $ this-> hasMany('App \ Comment','foreign_key','local_key');] – WindSaber