Load just ids of relation (pluck)

試著忘記壹切 提交于 2019-12-11 07:13:30

问题


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).

I want to load those users.

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:

I was hoping to just get users: [1, 12] for the example in the screenshot above.

I tried pluck like this return Pet::with('users')->get()->pluck('id') but this gives me only the ids.


回答1:


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']);

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();
  • Querying Relations, Querying Relationship Existence
  • Eager Loading, Eager Loading Specific Columns



回答2:


You can select specific fields like this:

Pet::with(['users' => function($query) { $query->select('id', 'name'); }])->get()


来源:https://stackoverflow.com/questions/46552285/load-just-ids-of-relation-pluck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!