問題描述
我是 laravel 和 eloquent 的新手,我不確定這是否可能.但我有 2 張表具有一對多的關系.一種是位置",一種是用戶".一個位置可以有多個用戶.
I'm new to laravel and eloquent and I'm not sure if this is even possible. but I have 2 tables with a one to many relationship. One is "locations" and one is "users". One location can have many users.
因此,如果我想獲取所有用戶的所有位置,我會這樣做:
So if I wanted to get all locations with all users I would just do this:
Location::with("users")->get();
但我也想知道每個位置有多少用戶,我嘗試這樣做
But I also want to know how many users each location has, I tried doing this
Location::with("users")->count("users")->get();
但這沒有用.
推薦答案
如果您使用預先加載,則不會出現(xiàn)提到的 n+1 問題.
The n+1 issue that was mentioned doesn't occur if you use eager loading.
$locations = Location::with('users')->get();
$locations->users()->count();
無論您有多少用戶或位置,這都會產生三個查詢.
This should result in three queries, no matter how many users or locations you have.
- 對位置模型進行計數(shù)查詢
- 從位置選擇 *
- select * from users where in
混淆是因為這也有效:
$locations = Location::all();
$locations->users()->count();
但在這種情況下,它會為每個位置查詢一次.
But in this case, it does query once for each location.
查看文檔了解更多信息:http://laravel.com/docs/eloquent#eager-loading
See the docs for more info: http://laravel.com/docs/eloquent#eager-loading
這篇關于Laravel 雄辯的計數(shù)關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!