加载关系的唯一ID(pluck) [英] Load just ids of relation (pluck)
问题描述
我有一个使用Laravel 5.5.13的简单应用程序.
I have a simple app, using Laravel 5.5.13.
public function index()
{
return Pet::all();
}
此列表列出了所有宠物.我有很多关系,许多用户可以拥有同一只宠物(宠物的人类家庭).
This lists all pets. I have many to many relation where many users can own a the same pet (the pet's human family).
我想加载这些用户.
执行return Pet::with('users')->get();
可以解决问题,但是它会加载所有种类繁多的信息,例如用户api_token等,我只想选择一些字段,例如id和name:
Doing return Pet::with('users')->get();
does the trick, however it loads all kind of excessive infromation, like the users api_token etc, I just want to pick some fields, like id and name:
我希望上面截图中的示例仅获得users: [1, 12]
.
I was hoping to just get users: [1, 12]
for the example in the screenshot above.
我尝试像这样return Pet::with('users')->get()->pluck('id')
拔毛,但这只给了我id.
I tried pluck like this return Pet::with('users')->get()->pluck('id')
but this gives me only the ids.
推荐答案
如果您只想获取所有匹配用户至少拥有一只宠物的用户ID,则可以尝试:
If you're only looking to get user IDs where all the matching users have at least one pet, you can try:
// Retrieve all users that have at least one pet
return User::has('pets')->get(['id']);
如果我误解了您,并且您仍然想要所有Pet信息,则可以使用冒号来获取关系中的特定列:
In case I'm misunderstanding you and you still want all of the Pet information, you can use a colon to fetch specific columns in a relation:
// Returns all Pets, along with their users' IDs
return Pet::with('users:id')->get();