加载关系的唯一ID(pluck) [英] Load just ids of relation (pluck)

查看:103
本文介绍了加载关系的唯一ID(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();

  • 查询关系,查询关系存在
  • 急切加载,急切加载特定列
    • Querying Relations, Querying Relationship Existence
    • Eager Loading, Eager Loading Specific Columns
    • 这篇关于加载关系的唯一ID(pluck)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆